Aarav Yadav
Aarav Yadav

Reputation: 1

Why does `document.getElementByTagName` not work?

I am unable to change the text inside my 'p' tag using this script

var firstItem = document.getElementByTagName('p');
firstItem.innerHTML = 'Adding Javascript';
<p> …?

Upvotes: -1

Views: 85

Answers (1)

jfriend00
jfriend00

Reputation: 707158

You have several coding errors. Here's some corrected code:

 <script>
 var firstItem = document.getElementsByTagName('p')[0];
 firstItem.innerHTML = 'Adding Javascript';
 </script>
  1. The correct method is document.getElementsByTagName('p'). Note the "s" at the end of "Elements".

  2. Then, because document.getElementsByTagName('p') returns an HTML collection object, you have to either iterate over the collection or reach into the collection to grab a specific DOM object (which I did in my example with [0]).

And here's a working code snippet:

// change just the first <p> tag
document.getElementById("test1").addEventListener("click", function(e) {
    var firstItem = document.getElementsByTagName('p')[0];
    firstItem.innerHTML = 'Adding Javascript';
});

// change all the <p> tags
document.getElementById("test2").addEventListener("click", function(e) {
    var items = document.getElementsByTagName('p');
    for (var i = 0; i < items.length; i++) {
      items[i].innerHTML = 'Setting All Items';
    }
});
<button id="test1">Change text of first item</button><br><br>
<button id="test2">Change text of all items</button><br><br>
<p>This is some text</p>
<p>This is more text</p>
<p>This is and more text</p>

Upvotes: 1

Related Questions