Javascript get children of element

Walking the DOM

The DOM allows us to do anything with elements and their contents, but first we need to reach the corresponding DOM object.

All operations on the DOM start with the document object. That’s the main “entry point” to DOM. From it we can access any node.

Here’s a picture of links that allow for travel between DOM nodes:

Let’s discuss them in more detail.

On top: documentElement and body

The topmost tree nodes are available directly as document properties:

= document.documentElement The topmost document node is document.documentElement . That’s the DOM node of the tag. = document.body Another widely used DOM node is the element – document.body . = document.head The tag is available as document.head .

A script cannot access an element that doesn’t exist at the moment of running.

In particular, if a script is inside , then document.body is unavailable, because the browser did not read it yet.

So, in the example below the first alert shows null :

        

In the DOM, the null value means “doesn’t exist” or “no such node”.

Children: childNodes, firstChild, lastChild

There are two terms that we’ll use from now on:

  • Child nodes (or children) – elements that are direct children. In other words, they are nested exactly in the given one. For instance, and are children of element.
  • Descendants – all elements that are nested in the given one, including children, their children and so on.

    but also more deeply nested elements, such as
    (a child of

      ) and (a child of
      ) – the entire subtree.

    The childNodes collection lists all child nodes, including text nodes.

    The example below shows children of document.body :

    Please note an interesting detail here. If we run the example above, the last element shown is . In fact, the document has more stuff below, but at the moment of the script execution the browser did not read it yet, so the script doesn’t see it.

    Properties firstChild and lastChild give fast access to the first and last children.

    They are just shorthands. If there exist child nodes, then the following is always true:

    elem.childNodes[0] === elem.firstChild elem.childNodes[elem.childNodes.length - 1] === elem.lastChild

    There’s also a special function elem.hasChildNodes() to check whether there are any child nodes.

    DOM collections

    As we can see, childNodes looks like an array. But actually it’s not an array, but rather a collection – a special array-like iterable object.

    There are two important consequences:

    for (let node of document.body.childNodes) < alert(node); // shows all nodes from the collection >

    That’s because it’s iterable (provides the Symbol.iterator property, as required).

    alert(document.body.childNodes.filter); // undefined (there's no filter method!)

    The first thing is nice. The second is tolerable, because we can use Array.from to create a “real” array from the collection, if we want array methods:

    alert( Array.from(document.body.childNodes).filter ); // function

    DOM collections, and even more – all navigation properties listed in this chapter are read-only.

    We can’t replace a child by something else by assigning childNodes[i] = . .

    Changing DOM needs other methods. We will see them in the next chapter.

    Almost all DOM collections with minor exceptions are live. In other words, they reflect the current state of DOM.

    If we keep a reference to elem.childNodes , and add/remove nodes into DOM, then they appear in the collection automatically.

    Collections are iterable using for..of . Sometimes people try to use for..in for that.

    Please, don’t. The for..in loop iterates over all enumerable properties. And collections have some “extra” rarely used properties that we usually do not want to get:

       

    Siblings and the parent

    Siblings are nodes that are children of the same parent.

    For instance, here and are siblings:

    • is said to be the “next” or “right” sibling of ,
    • is said to be the “previous” or “left” sibling of .

    The next sibling is in nextSibling property, and the previous one – in previousSibling .

    The parent is available as parentNode .

    // parent of is alert( document.body.parentNode === document.documentElement ); // true // after goes alert( document.head.nextSibling ); // HTMLBodyElement // before goes alert( document.body.previousSibling ); // HTMLHeadElement

    Element-only navigation

    Navigation properties listed above refer to all nodes. For instance, in childNodes we can see both text nodes, element nodes, and even comment nodes if they exist.

    But for many tasks we don’t want text or comment nodes. We want to manipulate element nodes that represent tags and form the structure of the page.

    So let’s see more navigation links that only take element nodes into account:

    The links are similar to those given above, just with Element word inside:

    • children – only those children that are element nodes.
    • firstElementChild , lastElementChild – first and last element children.
    • previousElementSibling , nextElementSibling – neighbor elements.
    • parentElement – parent element.

    The parentElement property returns the “element” parent, while parentNode returns “any node” parent. These properties are usually the same: they both get the parent.

    With the one exception of document.documentElement :

    alert( document.documentElement.parentNode ); // document alert( document.documentElement.parentElement ); // null

    The reason is that the root node document.documentElement ( ) has document as its parent. But document is not an element node, so parentNode returns it and parentElement does not.

    This detail may be useful when we want to travel up from an arbitrary element elem to , but not to the document :

    while(elem = elem.parentElement) < // go up till alert( elem ); >

    Let’s modify one of the examples above: replace childNodes with children . Now it shows only elements:

    Источник

    Element: children property

    The read-only children property returns a live HTMLCollection which contains all of the child elements of the element upon which it was called.

    Element.children includes only element nodes. To get all child nodes, including non-element nodes like text and comment nodes, use Node.childNodes .

    Value

    An HTMLCollection which is a live, ordered collection of the DOM elements which are children of node . You can access the individual child nodes in the collection by using either the item() method on the collection, or by using JavaScript array-style notation.

    If the element has no element children, then children is an empty list with a length of 0 .

    Examples

    const myElement = document.getElementById("foo"); for (const child of myElement.children)  console.log(child.tagName); > 

    Specifications

    Browser compatibility

    BCD tables only load in the browser

    See also

    Found a content problem with this page?

    This page was last modified on Apr 7, 2023 by MDN contributors.

    Your blueprint for a better internet.

    MDN

    Support

    Our communities

    Developers

    Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
    Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

    Источник

    Getting Child Elements of a Node in JavaScript

    Summary: in this tutorial, you will learn how to get the first child element, last child element, and all children of a specified element.

    Suppose that you have the following HTML fragment:

    html> html> head> meta charset="utf-8"> title>JS Get Child Elements title> head> body> ul id="menu"> li class="first">Home li> li>Products li> li class="current">Customer Support li> li>Careers li> li>Investors li> li>News li> li class="last">About Us li> ul> body> html>Code language: HTML, XML (xml)

    Get the first child element

    To get the first child element of a specified element, you use the firstChild property of the element:

    let firstChild = parentElement.firstChild; Code language: JavaScript (javascript)

    If the parentElement does not have any child element, the firstChild returns null . The firstChild property returns a child node which can be any node type such as an element node, a text node, or a comment node. The following script shows the first child of the #menu element:

    let content = document.getElementById('menu'); let firstChild = content.firstChild.nodeName; console.log(firstChild);Code language: JavaScript (javascript)
    #textCode language: CSS (css)

      and
      tags. This whitespace creates a #text node.

    Note that any whitespace such as a single space, multiple spaces, returns, and tabs will create a #text node. To remove the #text node, you can remove the whitespaces as follows:

    article id="content">h2>Heading h2>p>First paragraph p> article>Code language: HTML, XML (xml)

    Or to get the first child with the Element node only, you can use the firstElementChild property:

    let firstElementChild = parentElement.firstElementChild;Code language: JavaScript (javascript)

    The following code returns the first list item which is the first child element of the menu:

    let content = document.getElementById('menu'); console.log(content.firstElementChild);Code language: JavaScript (javascript)
    li class="first">Home li>Code language: HTML, XML (xml)
    • First, select the #menu element by using the getElementById() method.
    • Second, get the first child element by using the firstElementChild property.

    Get the last child element

    To get the last child element of a node, you use the lastChild property:

    let lastChild = parentElement.lastChild; Code language: JavaScript (javascript)

    In case the parentElement does not have any child element, the lastChild returns null . Similar to the the firstChild property, the lastChild property returns the first element node, text node, or comment node. If you want to select only the last child element with the element node type, you use the lastElementChild property:

    let lastChild = parentElement.lastElementChild;Code language: JavaScript (javascript)

    The following code returns the list item which is the last child element of the menu:

    let menu = document.getElementById('menu'); console.log(main.lastElementChild); Code language: JavaScript (javascript)
    li class="last">About Us li>Code language: HTML, XML (xml)

    Get all child elements

    To get a live NodeList of child elements of a specified element, you use the childNodes property:

    let children = parentElement.childNodes; Code language: JavaScript (javascript)

    The childNodes property returns all child elements with any node type. To get the child element with only the element node type, you use the children property:

    let children = parentElement.children;Code language: JavaScript (javascript)

    The following example selects all child elements of the element with the Id main :

    let menu = document.getElementById('menu'); let children = menu.children; console.log(children);Code language: JavaScript (javascript)

    JavaScript get child elements

    Summary

    • The firstChild and lastChild return the first and last child of a node, which can be any node type including text node, comment node, and element node.
    • The firstElementChild and lastElementChild return the first and last child Element node.
    • The childNodes returns a live NodeList of all child nodes of any node type of a specified node. The children return all child Element nodes of a specified node.

    Источник

    Читайте также:  Тег INPUT, атрибут readonly
Оцените статью