Get Child Elements with JavaScript and jQuery

In this tutorial, we will learn how to get children of an element in different ways using pure JavaScript and jQuery.

 

Get all Child Elements with JavaScript

To get all the child elements of an element with pure JavaScript, use the .children property. Let's try this out using the getElementById() method.

 

<div id="foo">
 <span>Element 1</span>
 <span>Element 2</span>
</div>
var children = document.getElementById('foo').children;

for (let i of children) {
  console.log(i);
  console.log(i.innerText);
}
<span>Element 1</span>
Element 1
<span>Element 2</span>
Element 2

 

Get Child Elements by Class Name with JavaScript

To get all child elements with a class name, loop through the children and evaluate if the class name is equal to something using the className property. If true, push the element to a new array which can be accessed later in the program.

 

<div id="foo">
  <span class="active">Element 1</span>
  <span class="disabled">Element 2</span>
  <span class="active">Element 3</span>
  <span class="disabled">Element 4</span>
</div>
var element = document.getElementById('foo').children;

var childrenActive = [];

// push children with the class "active" to a new array.

for (let i of element) {
  if (i.className == 'active') {
    childrenActive.push(i);
  }
}

// now access the children.

for (let e of childrenActive) {
  console.log(e);
  console.log(e.innerText);
}
<span class="active">Element 1</span>
Element 1
<span class="active">Element 3</span>
Element 3

 

Get all Child Elements with jQuery

To get all child elements with jQuery, use the children() method and store the result in a variable. To access elements in the object, loop through them or specify an index using [] (square brackets).

 

<div id="foo">
  <span>Element 1</span>
  <span>Element 2</span>
</div>
var children = $('#foo').children();

// access a single element by its index:

console.log(children[0]);

// loop through all the object elements and use them.

for (let i of children) {
  console.log(i);
  console.log(i.innerText);
}
<span>Element 1</span>
<span>Element 1</span>
Element 1
<span>Element 2</span>
Element 2

 

Get Child Elements with Class in jQuery

Use the find() method to get all child elements with a class name in jQuery.

 

<div id="foo">
  <span class="active">Element 1</span>
  <span class="disabled">Element 2</span>
  <span class="active">Element 3</span>
  <span class="disabled">Element 4</span>
</div>
children = $('#foo').find('.active');

for (let i of children) {
  console.log(i);
  console.log(i.innerText);
}
<span class="active">Element 1</span>
Element 1
<span class="active">Element 3</span>
Element 3
jquery