firstElementChild property
9 | 3.5 | |||
Returns a reference to the first child element of the current element.
Note: The firstElementChild property is supported in Firefox from version 3.5 and Internet Explorer from version 9.
The first child node and the first child element can be different.
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 first child node of an element, use the firstChild property.
The children collection contains all child elements of an element in source order. Since the children collection is supported widely by browsers, so you can use the first item from the children collection instead of the firstElementChild property.
Note: The children collection also contains the child comment nodes in Internet Explorer before version 9. In other browsers, it only contains the element nodes.
Similarly to the firstElementChild property, the lastElementChild property returns the last child element of an element, furthermore the nextElementSibling and previousElementSibling properties return the next and previous sibling element of an element.
Syntax:
You can find the related objects in the Supported by objects section below.
This property is read-only.
Possible values:
Reference to the first child element or null if it does not exist.
Default: this property has no default value.
Example HTML code 1:
This example illustrates the use of the firstElementChild and nextElementSibling properties:
|
||||
<head> <script type="text/javascript"> function GetListItems () { var list = document.getElementById ("myList"); if ('firstElementChild' in list) { var child = list.firstElementChild; while (child) { alert (child.innerHTML); child = child.nextElementSibling; } } else { var child = list.firstChild; while (child) { if (child.nodeType == 1 /*Node.ELEMENT_NODE*/) { alert (child.innerHTML); } child = child.nextSibling; } } } </script> </head> <body> <ol id="myList"> <li>Apple</li> <li>Peach</li> <li>Cherry</li> </ol> <button onclick="GetListItems ();">Get the list items!</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