sandeep sudhakaran
sandeep sudhakaran

Reputation: 31

JavaScript innerHTML is undefined

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

Answers (3)

user2855132
user2855132

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

user1751825
user1751825

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

isvforall
isvforall

Reputation: 8926

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);

Upvotes: 6

Related Questions