childElementCount property
9 | 3.5 | |||
Returns the number of element nodes that are direct descendants of the current element.
Note: The childElementCount property is supported in Firefox from version 3.5 and Internet Explorer from version 9.
The value returned by the childElementCount property contains the count of child element nodes, not the count of all child nodes.
A node is an element node if it's nodeType is 1 (Node.ELEMENT_NODE).
Text nodes and comment nodes are not element nodes.
If you need the child nodes of an element not only the number of them, use the children collection. It contains the child elements in source order.
Note that the children collection also contains the child comment nodes in Internet Explorer before version 9. In other browsers, it only contains the element nodes.
Since Internet Explorer does not support the childElementCount property before version 9, use the length property of the children collection in that browsers.Syntax:
You can find the related objects in the Supported by objects section below.
This property is read-only.
Possible values:
Integer that retrieves the number of child elements.
Default: this property has no default value.
Example HTML code 1:
This example illustrates the use of the childElementCount property and the children collection:
|
||||
<head> <script type="text/javascript"> function GetChildCount () { var container = document.getElementById ("container"); var childCount = 0; if ('childElementCount' in container) { childCount = container.childElementCount; } else { if (container.children) { childCount = container.children.length; } else { // Firefox before version 3.5 var child = container.firstChild; while (child) { if (child.nodeType == 1 /*Node.ELEMENT_NODE*/) { childCount++; } child = child.nextSibling; } } } alert ("The number of child elements is " + childCount); } </script> </head> <body> <div id="container" style="width:300px; background-color:#a0d0e0;"> Some text inside the container. <input type="text" size="40" value="a child element of the container" /> <div> <div>a descendant element of the container</div> <div>another descendant element of the container</div> </div> </div> <br /><br /> <button onclick="GetChildCount ();">Get the number of container's child elements</button> </body> |
||||
|
||||
Did you find this example helpful?
|
Supported by objects:
HTML elements:
a, abbr, acronym, address, applet, b, bdo, big, blink, blockquote, body, button, caption, center, cite, code, col, colgroup, dd, del, dfn, dir, div, dl, dt, em, fieldset, font, form, frameset, h1, h2, h3, h4, h5, h6, head, html, i, img, ins, kbd, keygen, label, legend, li, listing, map, marquee, menu, nobr, noframes, noscript, object, ol, optgroup, option, p, plaintext, pre, q, rt, ruby, s, samp, select, small, span, strike, strong, sub, sup, table, tbody, td, textarea, tfoot, th, thead, tr, tt, u, ul, var, xmp
Related pages:
External links:
User Contributed Comments