Mehdi khosravi
Mehdi khosravi

Reputation: 319

why undefined returns in getElementByTagName

I use below code to get the count of p tags in my html document.I have 2 p tags, but this code returns "undefined" for me :

document.write(document.getElementsByTagName('p').childElementCount);

Upvotes: 1

Views: 88

Answers (2)

Bryan Ray
Bryan Ray

Reputation: 929

This should work for you.

console.log(document.getElementsByTagName('p').length)

You can also do this, if you want to get the childElements:

var paragraphs = document.getElementsByTagName('p');
console.log(paragraphs[0].childElementCount);

The problem you're facing is that getElementsByTagName is returning an array-like object of paragraph elements. You need to get one of those elements and then you can call childElementCount on that element.

Paste the above in to the Chrome Console debugger and you should see a value output.

http://jsfiddle.net/bryanray/pwaj4yjd/

Upvotes: 0

James Donnelly
James Donnelly

Reputation: 128791

childElementCount returns the number of children an individual Node contains.

document.getElementsByTagName() returns a HTMLCollection - containing a collection of Node objects - which doesn't have a childElementCount property.

To get the total number of elements contained within a HTMLCollection, you can simply use its length property:

document.getElementsByTagName('p').length;

Upvotes: 1

Related Questions