getElementsByTagName() method doesnt work as expec

2020-04-21 06:15发布

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?

4条回答
Explosion°爆炸
2楼-- · 2020-04-21 06:56

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

查看更多
We Are One
3楼-- · 2020-04-21 06:58

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楼-- · 2020-04-21 07:16

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";
}
查看更多
狗以群分
5楼-- · 2020-04-21 07:18

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";
}
查看更多
登录 后发表回答