Getelementsbytagname() Method Doesnt Work As Expected
I'm trying to simply change the text inside all elements with this code
You have to set the index of your HTMLCollection/NodeList.
elem=document.getElementsByTagName("p");
elem[0].innerHTML="work";
You can also do it for each p
tag in your HTML document.
var elem = document.getElementsByTagName("p");
for(var index = 0; index < elem.length; index++){
elem[index].innerHTML="work";
}
Solution 2:
It returns a NodeList
which you need to loop:
var elements = document.getElementsByTagName("p");
for(var i = 0; i < elements.length; i++){
elements[i].innerHTML="work";
}
Solution 3:
it returns list of elements
if you have one then you might use:
document.getElementsByTagName('p')[0]
if you want to apply it to multiple
then you have to iterate over the list
var list = document.getElementsByTagName('p')
for(index in list){
list[index].innerHTML = 'work';
}
Solution 4:
Assuming you have jquery included you can do it as following:
$("p").text("work");
or better
$(document).ready(function(){
$("p").text("work");/*when the dom of the page is fully loaded text inside p tags will be changed to "work"*/
});
That way you have a faster cross browser sollution
Post a Comment for "Getelementsbytagname() Method Doesnt Work As Expected"