JavaScript, getElementsByClassName method not working | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

JavaScript, getElementsByClassName method not working

<div class = 'demo'> <p> some text </p> <p> some other text </p> <p> testing 123 </p> </div> <script type="text/javascript"> var divelem = document.getElementsByClassName('demo') var arry = divelem.childNodes for(var v = 0;v < arry.length;v++){ arr[v].innerHTML = 'new text' } </script> But This works when I use Id instead of class in the whole script.

11th Jun 2020, 1:37 PM
Gaurav Giri
Gaurav Giri - avatar
2 Answers
+ 2
You should look up the difference between getElementsByClassName and getElementByIdName If you see one things it is elements in class and element in id basically getElementsByClassName returns an array of classes with same name So you need to choose whatever element no. you want to target by divelem[0] or divelem[1] or so
11th Jun 2020, 2:09 PM
Abhay
Abhay - avatar
0
There can be multiple classes with the same name. So js takes class elements as an array. Eg: //Get value var list = document.getElementsByClassName("example")[0]; //Set value list.getElementsByClassName("child")[0].innerHTML = "Milk"; So. you have to add [0] to work with getElementsByClassName.
11th Jun 2020, 2:11 PM
Sharique Khan
Sharique Khan - avatar