Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getElementsByTagName within an element javascript

Tags:

javascript

dom

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>
like image 334
Sam Adamsh Avatar asked Mar 24 '12 07:03

Sam Adamsh


People also ask

What is getElementsByTagName in JavaScript?

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.

How do I find the tag name of an element?

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

How do you iterate through getElementsByTagName?

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.

Can I select multiple tags using getElementsByTagName?

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.


1 Answers

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>​
like image 121
Tomalak Avatar answered Oct 11 '22 17:10

Tomalak