2015-11-06 23 views
1

爲什麼未定義回報我用下面的代碼來獲取p標籤計數在我的HTML document.I有2個p標籤,但是這個代碼返回"undefined"對我來說:在getElementByTagName

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

'document.getElementsByTagName'返回** **集合的元素,你需要在它們之間迭代 – Tushar

+0

如果你只是想要計數,那麼使用'.length',而不是'.childElementCount' – mariocatch

+0

你可以嘗試@Tushar的方法,看看它是否給你相同的結果 - 但.length似乎滿足你的需求,基於什麼你問。 – mariocatch

回答

0

這應該爲你工作。

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

你也可以做到這一點,如果你想獲得childElements:

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

你面臨的問題是,getElementsByTagName將返回段落元素的數組狀物體。您需要獲得一個這些元素,然後您可以在該元素上調用childElementCount

將上述內容粘貼到Chrome控制檯調試器中,您應該看到值輸出。

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

+0

我不能用'.childElementCount'在這裏計數,對吧? –

+0

當然可以。以示例更新。 –

+1

它不是元素的「數組」,它是一個活的[HtmlCollection](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection)。 – epascarello

1

childElementCount返回兒童的個人Node包含的數量。

document.getElementsByTagName()返回HTMLCollection - 含Node對象的集合 - 這不具有childElementCount財產。

要獲得包含在HTMLCollection中的元素的總數量,你可以簡單地使用其length屬性:

document.getElementsByTagName('p').length;