Element.length

  • Revision slug: Web/API/element.length
  • Revision title: element.length
  • Revision id: 477023
  • Created:
  • Creator: kscarfone
  • Is current revision? Yes
  • Comment Updated tags

Revision Content

{{ DomRef() }}

Summary

length returns the number of items in a NodeList.

Syntax

numItems =nodeList.length
  • numItems is an integer value representing the number of items in a NodeList.

Example

// all the paragraphs in the document 
var items = document.getElementsByTagName("p"); 
// for each item in the list,
// append the entire element as a string of HTML
var gross = "";
for (var i = 0; i < items.length; i++) {
  gross += items[i].innerHTML;
}
// gross is now all the HTML for the paragraphs

Notes

Despite the location of this page in the reference, length is not a property of Element, but rather of a NodeList. NodeList objects are returned from a number of DOM methods, such as document.getElementsByTagName.

length is a very common property in DOM programming. It's very common to test the length of a list (to see if it exists at all) and to use it as the iterator in a for loop, as in the example above.

Specification

length

{{ languages( { "ja": "ja/DOM/element.length", "pl": "pl/DOM/element.length" } ) }}

Revision Source

<p>{{ DomRef() }}</p>
<h3 id="Summary" name="Summary">Summary</h3>
<p><code>length</code> returns the number of items in a <code>NodeList</code>.</p>
<h3 id="Syntax" name="Syntax">Syntax</h3>
<pre class="eval">
<i>numItems</i> =<i>nodeList</i>.length
</pre>
<ul>
  <li><code>numItems</code> is an integer value representing the number of items in a <code>NodeList</code>.</li>
</ul>
<h3 id="Example" name="Example">Example</h3>
<pre>
// all the paragraphs in the document 
var items = document.getElementsByTagName("p"); 
// for each item in the list,
// append the entire element as a string of HTML
var gross = "";
for (var i = 0; i &lt; items.length; i++) {
  gross += items[i].innerHTML;
}
// gross is now all the HTML for the paragraphs
</pre>
<h3 id="Notes" name="Notes">Notes</h3>
<p>Despite the location of this page in the reference, <code>length</code> is not a property of <a href="en/DOM/element">Element</a>, but rather of a <code>NodeList</code>. NodeList objects are returned from a number of DOM methods, such as <a href="en/DOM/document.getElementsByTagName">document.getElementsByTagName</a>.</p>
<p><code>length</code> is a very common property in DOM programming. It's very common to test the length of a list (to see if it exists at all) and to use it as the iterator in a for loop, as in the example above.</p>
<h3 id="Specification" name="Specification">Specification</h3>
<p><a class="external" href="http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-203510337">length</a></p>
<p>{{ languages( { "ja": "ja/DOM/element.length", "pl": "pl/DOM/element.length" } ) }}</p>
Revert to this revision