Reputation: 31
Struggling with why .innerHTML shows undefined, yet .length shows 1.
var content = document.getElementsByTagName("h1");
console.log(content.innerHTML);
console.log(content.length);
<h1>Hello World</h1>
<ul>
<li>This is an item</li>
<li>This is another item</li>
</ul>
Upvotes: 2
Views: 16688
Reputation:
JavaScript's document.getElementsByTagName
returns an (array-like) object. You can to get the one element you need with content[0]
:
//returns a collection of elements
var content = document.getElementsByTagName("h1");
// single out the element you need
var tag = content[0];
console.log(typeof(content));
console.log(content.length);
//get the element's inner HTML
console.log(tag.innerHTML);
<h1>Hello World</h1>
<ul>
<li>This is an item</li>
<li>This is another item</li>
</ul>
Upvotes: 2
Reputation: 4309
If you need to target this element specifically, give it an id attribute, and then use getElementById. This is more efficient, and will return just a single element.
Upvotes: 0