2

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>

1
  • 3
    getElementsByTagName returns a list. So you want index 0 of the result, like this: document.getElementsByTagName("h1")[0].innerHTML Commented Feb 20, 2016 at 22:44

3 Answers 3

6

From MDN

The Element.getElementsByTagName() method returns a live HTMLCollection of elements with the given tag name.

Use [0] to get first item:

console.log(content[0].innerHTML);
Sign up to request clarification or add additional context in comments.

Comments

2

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>

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.