Javascript get all child elements

How to get the children of an element in vanilla JS

In jQuery, there are two methods you can use to get an element’s children. The contents() method will get all child nodes including comment and text nodes. The children() method will only get children that are HTML elements. Here’s how to do this in vanilla JS with browser support back to IE9.

For the examples in this post, assume the following HTML. I’ve deliberately added a comment and some liberal spacing:

ul id="rainbow">



li>Redli>

li>Orangeli>

li>Yellowli>

li>Greenli>

li>Blueli>

li>Indigoli>

li>Violetli>

ul>

Get all child nodes

To get all child nodes of an element, including comment and text nodes, you can use the Node.childNodes property:

// Get the #rainbow element
var rainbow = document.querySelector("#rainbow");

// Save its childNodes property to a variable
var coloursOfRainbow = rainbow.childNodes;

// NodeList(17) [ #text, , #text, li, #text, li, #text, li, #text, li, … ]
console.log(coloursOfRainbow);

This property is supported back to IE5.

Get HTML children only

To only get children that are HTML elements, you can use the ParentNode.children property:

// Get the #rainbow element
var rainbow = document.querySelector("#rainbow");

// Save its children property to a variable
var coloursOfRainbow = rainbow.children;

// HTMLCollection
console.log(coloursOfRainbow);

This property is supported back to IE9.

Converting into true arrays

The childNodes property contains a NodeList while the children property contains an HTMLCollection .

It’s usually a good idea to convert these into true arrays before trying to manipulate them. All of the following will work:

// (Also works for rainbow.children)
var coloursOfRainbow = rainbow.childNodes;

// The most well-supported method
coloursOfRainbow = Array.prototype.slice.call(coloursOfRainbow);

// ES6 only (CAN be polyfilled)
coloursOfRainbow = Array.from(coloursOfRainbow);

// ES6 only (CANNOT be polyfilled)
coloursOfRainbow = [. coloursOfRainbow];

Summary

  • Use the Node.childNodes property to get all of an element’s children.
  • Use the ParentNode.children property to only get HTML children.

👋 Got questions or comments? Email me at kieran@barker.codes.

Copyright © 2023 Kieran Barker. Proudly built with Eleventy and hosted by Netlify.

Источник

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.

Источник

How to get the children of an element using JavaScript

To get all child nodes of an element, you can use the childNodes property. This property returns a collection of a node’s child nodes, as a NodeList object.

By default, the nodes in the collection are sorted by their appearance in the source code. You can use a numerical index (start from 0) to access individual nodes.

Let us say you have the following HTML code:

ul id="langs"> li>JavaScriptli> li>Nodeli> li>Javali> li>Rubyli> li>Rustli> ul> 

    tag and print their content:

const ul = document.querySelector('#langs'); // get all children const childern = ul.childNodes; // iterate over all child nodes childern.forEach(li =>  console.log(li.innerText); >); 

Here is how the output looks like:

undefined JavaScript undefined Node undefined Java undefined Ruby undefined Rust undefined 

Wait, why undefined appears in the output?

This is because whitespace inside elements is considered as text, and text is treated as nodes. It also applies to comments that are considered as nodes too.

If you want to exclude comment and text nodes, use the children property instead. This property returns a collection of a node’s element nodes only, as an HTMLCollection object:

const children = ul.children; // iterate over all child nodes Array.from(children).forEach(li =>  console.log(li.innerText); >); 

Here is how the output looks like now:

JavaScript Node Java Ruby Rust 

The difference between childNodes and children is that childNodes returns a NodeList object containing all nodes, including text nodes and comment nodes, while children returns an HTMLCollection object only containing element nodes.

To get the first and last children of an element, JavaScript provides firstChild and lastChild properties:

const ul = document.querySelector('#langs'); // get first children const firstChild = ul.firstChild; // get last children const lastChild = ul.lastChild; 

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

Читайте также:  Python ndarray to json
Оцените статью