+ 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.
2 Respuestas
+ 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
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.