getElementsByTagName() method doesnt work as expec

2020-04-21 06:35发布

问题:

I'm trying to simply change the text inside all </p> elements with this code

<html>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<body>
    <p></p>
    <script>
        elem=document.getElementsByTagName("p");
        elem.innerHTML="work";
    </script>
</body>
</html>

from this I expect work to appear on the page, but the result is just a blank page with no text. why?

回答1:

getElementsByTagName is method of the DOM interface. It accepts a tag name as input and returns a NodeList (some browsers chose to return HTMLCollection instead, which is OK, since it is a superset of NodeList).

Difference between HTMLCollection, NodeLists, and arrays of objects

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";
}


回答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";
}


回答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';
}


回答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