1

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?

lychee
  • 1,771
  • 3
  • 21
  • 31

4 Answers4

5

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";
}
Community
  • 1
  • 1
roemel
  • 3,247
  • 4
  • 29
  • 52
  • Well, actually its not an array but a HTMLCollection. See more at http://stackoverflow.com/questions/15763358/difference-between-htmlcollection-nodelists-and-arrays-of-objects – Pavelloz Apr 12 '15 at 10:48
1

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";
}
Jon Snow
  • 3,682
  • 4
  • 30
  • 51
0

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';
}
robert
  • 66
  • 1
  • 3
0

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

cssGEEK
  • 994
  • 2
  • 15
  • 38