Document.getElementByClassName not working [duplicate] - javascript

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 6 years ago.
I'm trying to use Document.getElementByClassName, but it isn't working. I've included my code below. I'd appreciate any help.
HTML document:
<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>Day Practice</title>
<style></style>
</head>
<body>
<h1 class=myclass> Some text</h1>
</body>
</html>
JavaScript code:
var change = document.getElementByClassName("myclass");
change.innerHTML = "New text";

It's getElementsByClassName Elements
Returns an array-like object of all child elements which have all of the given class names
- Mozilla Developer Network / Document.getElementsByClassName()
Loop through it or use change[0].innerHTML
1
var change = document.getElementsByClassName("myclass");
change[0].innerHTML = "New text";
<h1 class="myclass"> Some text</h1>
2
var change = document.getElementsByClassName("myclass");
for (var i = 0; i < change.length; i++) {
change[i].innerHTML = "New text";
}
<h1 class="myclass"> Some text</h1>

Right before the closing body tag (), you want to add a script tag to attach your JavaScript file into the HTML file, so that they're both linked.
This is how it should look:
<head>
<meta charset=utf-8>
<title>Day Practice</title>
<style></style>
</head>
<body>
<h1 class=myclass> Some text</h1>
<script src="javascriptfile.js"></script>
</body>
Also, it's "getElementsByClassName"; elements is plural

Related

Generate random fact from an array [duplicate]

This question already has an answer here:
Why am I getting "ReferenceError: getElementById is not defined"?
(1 answer)
Closed 2 years ago.
I was trying to make a random fact generator website which would generate some random facts from an array, This is how I expected it to work - First I created a button which on click would generate a random fact but unfortunately The button is not working. Please check the code below and tell me the mistakes that I made.
Code below
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Facts generator website</title>
</head>
<body>
<div id="container">
<button id="btn" onclick="generateFacts()">Click me!</button>
<div id="here">
</div>
</div>
<script>
var facts = ["I will add more facts later" , 'Heaven']
var randomFact = randomlist(facts);
function generateFacts(){
getElementById('here').innerHTML = randomFact;
}
function randomlist(list){
var x = Math.floor(Math.random() * list.length);
return list[x];
}
</script>
</body>
</html>
There is no function called getElementById alone. You need to use the method inside document object. So, the function will be document.getElementById()
var facts = ["I will add more facts later", 'Heaven']
var randomFact = randomlist(facts);
function generateFacts() {
document.getElementById('here').innerHTML = randomFact;
}
function randomlist(list) {
var x = Math.floor(Math.random() * list.length);
return list[x];
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Facts generator website</title>
</head>
<body>
<div id="container">
<button id="btn" onclick="generateFacts()">Click me!</button>
<div id="here">
</div>
</div>
</body>
</html>
How about document.getElementById()?
function generateFacts(){
document.getElementById('here').innerHTML = randomFact;
}
If you open the developer console you should see the error that points out the mistake:
The function getElementById is not defined.
So the function generateFacts should look like this:
function generateFacts(){
document.getElementById('here').innerHTML = randomFact;
}
document is the owner of all the DOM elements of the page. So you should call it to help you find the element.

Why I need 4 previousSibling to get 2 previous element? [duplicate]

This question already has answers here:
How does NextSibling work?
(2 answers)
Closed 4 years ago.
In this example, I want to get the value of 2 previous sibling
But this is not work btn.previousSibling.previousSibling.value
I need use 4 previousSibling to get the value, why 4?
<!DOCTYPE HTML>
<html>
<head>
<script>
function text(btn){
console.log(btn.previousSibling.previousSibling.previousSibling.previousSibling.value)
}
</script>
</head>
<body>
<textarea></textarea>
<br>
<button onclick="text(this)">text</button>
</body>
</html>
previousSibling points to the previous Node, which is new line (a TextNode) in your example. You might want to use previousElementSibling instead
function text(btn){
console.log(
btn
.previousElementSibling
.previousElementSibling
.value
);
}
<textarea>Hello</textarea>
<br>
<button onclick="text(this)">text</button>
It can be because of empty entries inserted by the browser :
https://developer.mozilla.org/en-US/docs/Web/API/Node/previousSibling
this code works in your case :
<!DOCTYPE HTML>
<html>
<head>
<script>
function text(btn){
alert(btn.previousSibling.previousSibling.value);
}
</script>
</head>
<body>
<textarea>test text</textarea><br><button onclick="text(this)">text</button>
</body>
</html>
You can use JQuery $(btn).prev().prev();
Like :
<!DOCTYPE HTML>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
function text(btn){
alert($(btn).prev().prev().val());
}
</script>
</head>
<body>
<textarea>test text</textarea>
<br>
<button onclick="text(this)">text</button>
</body>
</html>
The reason is because of the br element.
You can get the parent using parentNode and queryselector to get the specific element.
function text(btn) {
var getText = btn.parentNode.querySelector('textarea').value;
console.log(getText.trim())
}
<textarea></textarea>
<br>
<button onclick="text(this)">text</button>

Usage of "document.getElemenentsByTagName()" in JS [duplicate]

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 5 years ago.
i'm relatively new to html and JS. I have done my research about "document.getElementsByTagName()" but didn't understand much.
I need to do a page that has 2 headings, one combobox and 1 button. When the onclick at the button is triggered the heading must change its background color depending on the option that is chosen at the combobox and decolorize with the same technique. Here is what i 've done so far:
function colorDiscolor() {
var getButton=document.getElementById('b1');
var element=document.getElementById('combo');
var optionValue=element.options[element.selectedIndex].value;
if (getButton.value=="Colorize") {
getButton.value="Decolorize";
if (optionValue=="level_1") {
//obviously wrong
document.getElementsByTagName('h1').style.backgroundColor="yellow";
}
else {
//obviously wrong
document.getElementsByTagName('h2').style.backgroundColor="yellow";
}
}
else {
getButton.value="Colorize";
if (optionValue=="level_1") {
//obviously wrong
document.getElementsByTagName('h1').style.backgroundColor="white";
}
else {
//obviously wrong
document.getElementsByTagName('h2').style.backgroundColor="white";
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Ex17</title>
<script type="text/javascript" src="Script.js"></script>
</head>
<body>
<div id="h">
<h1>This is h1</h1>
<h2>This is h2</h2>
</div>
<div>
<select id="combo">
<option value="level_1">Level 1</option>
<option value="level_2">Level 2</option>
</select>
<input type="button" id="b1" value="Colorize"
onclick="colorDiscolor()"/>
</div>
</body>
</html>
The answer will help me settle things in my mind about this method.
(No JQuery)
Cheers!
document.getElementsByTagName returns a collection of elements.
https://www.w3schools.com/jsref/met_document_getelementsbytagname.asp
You need to specify index 0 to get the first, and in your case only, element.
document.getElementsByTagName('h1')[0].style.backgroundColor="yellow";

Unable to set property 'onclick' of undefined or null reference [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 7 years ago.
I made new project in Visual Studio 2015. It's JavaScript Windows App. I'm trying to make "Hello" application, but when i want compile it i get this error:
0x800a138f - JavaScript runtime error: Unable to set property 'onclick' of undefined or null reference
My code:
document.getElementById("button").onclick = function () {
var jmeno = document.getElementById("Jmeno").value
var pop = new Windows.UI.Popups.MessageDialog("<%=Ahoj.Clientid%>" + jmeno);
pop.showAsync()
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>App1</title>
<!-- WinJS references -->
<link href="WinJS/css/ui-dark.css" rel="stylesheet" />
<script src="WinJS/js/base.js"></script>
<script src="WinJS/js/ui.js></script>
<!-- App1 references -->
<link href="/css/default.css" rel="stylesheet" />
<script src="/js/default.js"></script>
<script src="js/zdravic.js"></script>
</head>
<body class="win-type-body">
<header>
<h1>Hello user! :)</h1>
</header>
<section>
<input id='Jmeno' type="text" placeholder="Zadej své jméno"/>
<button id="button">Klikni na mě!</button>
</section>
</body>
</html>
And for more, default.css doesn't work for me. Like it wouldn't be there. And yes, i have link it there.
You are trying to access an element, which has not been loaded yet,
try:
window.onload=function(){
document.getElementById("button").onclick = function () {
var jmeno = document.getElementById("Jmeno").value;
var pop = new Windows.UI.Popups.MessageDialog("<%=Ahoj.Clientid%>" + jmeno);
pop.showAsync();
}
}

getElementsByTagName is not working Simple JS

another quesion: http://jsfiddle.net/ajinkyax/qGzTY/1/
Above link shows a js calculator, but whn u click nothign happens
Im just amazed why this simple function not working!!!.
I even tested with a tag, still it wont wokr. getElementsByTagName("a")
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>documentElement</title>
</head>
<body>
<p>This is 4rth child (3)</p>
<p>This is 4rth child (3)</p>
<p>This is 5th child (4) <span id="some">CHANGE THIS</span></p>
<script type="text/javascript">
var mySpan = document.getElementsByTagName('span');
mySpan.innerHTML = 'This is should change';
</script>
</body>
</html>
Do this :
var mySpan = document.getElementsByTagName('span')[0];
mySpan.innerHTML = 'This is should change';
getElementsByTagName doesn't return an element but a collection of all elements having this tag name. If you want only the first one, add [0].
As was pointed by user1689607, if you want to change just this specific span, you'd better do
var mySpan = document.getElementById('some');

Categories

Resources