Why does getElementById work but not getElementByClassName? [duplicate] - javascript

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 5 years ago.
I recently starting learning JS and for some reason I cannot get getElementByClassName to work for me. Here's my code.
//variable to store the ID h1
var id = document.getElementById("first");
//variable to store the class h1
var cs = document.getElementsByClassName("second");
//coloring the id 'first'
id.style.color = "red";
cs.style.color = "blue";
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test Site</title>
</head>
<body>
<h1 id="first">This is an ID</h1>
<h1 class="second">This is a class</h2>
<script src="index.js"></script>
</body>
</html>
The element with an ID is changing color but the one with a class isn't. Any help would be greatly appreciated.

getElementById returns one single element as you should not have multiple element with the same Id in the DOM.
getElementsByClassName returns an HTMLCollection as many elements can share the same class name.
try this instead :
//variable to store the ID h1
var id = document.getElementById("first");
//variable to store the class h1
var cs = document.getElementsByClassName("second");
//coloring the id 'first'
id.style.color = "red";
cs[0].style.color = "blue";
In real life use case you might wanna loop through the array.

Related

Uncaught TypeError: Cannot set property 'innerHTML' of null :( [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 2 years ago.
i think that the code 100% normal but why i got that Error????:
Uncaught TypeError: Cannot set property 'innerHTML' of null||
the code is:
<!DoCTYPE html>
<html lang="eng">
<head>
<meta charset ="utf-8">
<meta name="" content="">
<title></title>
<script>
function myAgeInDays() {
"use strict";
var myAge = 15;
return myAge * 365;
}
var daysCalc = myAgeInDays();
document.getElementById("test").innerHTML =
"Your Age In Days = "+ daysCalc+ " Day";
</script>
</head>
<body>
<button onclick="myinfo();">OK</button>
<h1 id="test">Ok</h1>
</body>
</html>
A few things can be done to improve this question:
Give some context, not the error the console prints out
Especially in the case of a very common js error. An example for your case could be "In form submission cannot select html element / selector is null in onclick function".
State some of the things you have tried
This will help you grow as a developer (the old teaching someone to fish story)
Some more tips here: https://stackoverflow.com/help/how-to-ask
In your case, the code you posted does not work (myinfo is not defined) and your code is in the <head> which is defined before the <p> is created. add it at the end of your body to ensure that all the elements are created. If you wanted to make a function handle the button click that contained the logic in your , you would write something like:
<body>
<button id="calcDays">OK</button>
<h1 id="test">Ok</h1>
<script type="text/javascript">
document.getElementById('calcDays')
.addEventListener('click', function () {
function myAgeInDays(days) {
return days * 365;
}
document.getElementById("test").textContent =
`Your Age In Days = ${myAgeInDays(15)} Days`;
});
</script>
</body>

Getting a 'cannot set property 'onclick' Error' [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 4 years ago.
I am a beginner in Javascript. I am doing some exercises and coming across the error listed above for the 'onclick'.
I have looked at other questions on this forum and it has not be helpful for me. I have looked over syntax numerous times in both my html and JS and can't find anything!
var item1;
var item2;
var item3;
document.getElementById("changeList").onclick = newList;
function newList() {
item1 = prompt("Enter a new first thing:");
item2 = prompt("Enter a new second thing:");
item3 = prompt("Enter a new third thing:");
updateList();
}
function updateList() {
document.getElementById("firstThing").innerHTML = item1;
document.getElementById("secondThing").innerHTML = item2;
document.getElementById("thirdThing").innerHTML = item3;
}
<html>
<head>
<meta charset="UTF-8">
<title>Javascript Practice</title>
<script src="main.js"></script>
</head>
<body>
<h1 id="myName">Angie</h1>
<hr>
<p id="aboutMe"><em>I am trying to learn this damn javascript and stick with it.</em></p>
<h2>Things I like</h2>
<p>Here are some of the things I like to do:</p>
<ul>
<li id=firstThing>Dance</li>
<li id=secondThing>Write</li>
<li id=thirdThing>Travel</li>
</ul>
<button id="changeList" type="button">Change Your List</button>
</body>
</html>
You can try placing your script tag at the bottom of the page as suggested by lealceldeiro or you can wait for the DOM to load fully before adding your event listener for onclick like so:
//Replace this line
document.getElementById("changeList").onclick = newList;
//With the following, this fires an event when the DOM has fully loaded
//This will ensure your element has been rendered into the DOM
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementById("changeList").onclick = newList;
});
Try changing your html line to :
<button id="changeList" type="button" onclick = newList();>Change Your List</button>
and remove this line from your JS
document.getElementById("changeList").onclick = newList;

Using data-* with javascript [duplicate]

This question already has answers here:
Access 'data-' attribute without jQuery
(5 answers)
Closed 8 years ago.
I am learning javascript and trying to store the value 2 in data-value in img element, and when I press the image I want to use javascript to show that value(2) in a paragraph. Here's my code:
<!DOCTYPE html>
<html>
<head>
<script>
function ispisi() {
var x = document.getElementById("myimage").data-value;
document.getElementById('demo').innerHTML = x;
}
</script>
</head>
<body>
<img id="myimage" data-value="2" onclick="ispisi()" src="bulboff.gif" width="100" height="180" />
<p id="demo">Text here<p>
</body>
</html>
The value should show in paragraph p, but when I click the image "text here" stays, insted. Why is this code not working?
try this
var x = document.getElementById("myimage").dataset.value;
OR
var x = document.getElementById("myimage").getAttribute("data-value");
The proper way to do this would be as follows:
function ispisi() {
var x = document.getElementById("myimage").getAttribute('data-value');
document.getElementById('demo').innerHTML = x;
}
window.onload = function() {
document.getElementById('myimage').onclick = ispisi;
};

How can I use html tag in this javascript? [duplicate]

This question already has answers here:
Changing the way a JavaScript Alert() or Prompt() looks
(4 answers)
Closed 8 years ago.
How can I use html tag in this javascript?
First of all, why <br> doesn't work in prompt. Secondly, why can't I use tags for this code (poundOne.pound) to make the font larger by using css or html code such as <h1>, <h2>, <h3>... or <div style="......">?
<html>
<head>
<script type="text/javascript">
function poundToKgConvertor( pound ){
this.pound = pound;
this.convertorDon = convertor;
}
function convertor(){
var convert = this.pound * 0.453592;
return convert;
}
var poundOne = new poundToKgConvertor(prompt ("Convert Pound to Kilogram!<br> Please insert your number of pound!"));
</script>
</head>
<body>
<script type="text/javascript">
document.write(poundOne.pound + " Pound = " + poundOne.convertorDon() + " <b>Kilogram</b>");
</script>
</body>
</html>
You can't use HTML in prompt/alert dialogs. However you can use new line characters:
prompt ("Convert Pound to Kilogram!\n Please insert your number of pound!");

why it is printing [object] as alert [duplicate]

This question already has answers here:
How do I get the value of text input field using JavaScript?
(16 answers)
Closed 8 years ago.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
user name:
<input type="text" id="t1">
<br>
<button type="button" onClick="myFunction()">display</button>
<script type="text/javascript">
function myFunction() {
var str;
str = document.getElementById("t1");
alert(str);
}
</script>
</body>
</html>
In the above program it is displaying [object] inside the alert box,I don't know why,I want to display what ever user input in the text box.help me..........
You're only getting the html element which is represented as an object, not the actual contents of the <input>. You need to explicitly get that content using .value:
function myFunction() {
var str;
str = document.getElementById("t1").value;
alert(str);
}
Change:
str = document.getElementById("t1")
to:
str = document.getElementById("t1").value;
jsFiddle example
document.getElementById("t1") refers to the element so you need to specify the property of the element you want. In this case, the value.
Your str variable contains a reference to the object itself, not the text inside. What you want is:
str = document.getElementById('t1').value;
You should use t1.value in the alert. t1 is the whole input element but you are only interested at what has been entered i.e. its value.
rather than alert(str), use console.log(str), then check browsers console

Categories

Resources