Why does the following return 0?
<p id="g">
<div>kk</div>
<div>ee</div>
<div>jff</div>
</p>
<script type="text/javascript">
var ii = document.getElementById("g");
var hh = ii.getElementsByTagName('div');
document.write(hh.length);
</script>
Definition and Usage The getElementsByTagName() method returns a collection of all elements with a specified tag name. The getElementsByTagName() method returns an HTMLCollection. The getElementsByTagName() property is read-only.
The tagName read-only property of the Element interface returns the tag name of the element on which it's called. For example, if the element is an <img> , its tagName property is "IMG" (for HTML documents; it may be cased differently for XML/XHTML documents).
After selecting elements using the querySelectorAll() or getElementsByTagName() , you will get a collection of elements as a NodeList . To iterate over the selected elements, you can use forEach() method (supported by most modern web browsers, not IE) or just use the plain old for-loop.
You can select multiple tags using getElementsByTagName for the purpose of having one iterable array, where results for multiple tags e.g. P and LI could be processed together.
Because you can't have a <div>
in a <p>
. Paragraphs can only have inline elements as children.
As soon as the parser encounters a <div>
, it auto-closes the <p>
.
Compare
<p id="g">
<span>kk</span>
<div>ee</div>
<div>jff</div>
</p>
<script type="text/javascript">
var ii = document.getElementById("g");
var hh = ii.getElementsByTagName('span');
alert(hh.length);
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With