How to select all children of an element with javascript and change CSS property?

If there's only one parent element then we can use querySelector to select all the children of that element

HTML

<div class="parent">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
</div>

JS

let children = document.querySelector(".parent").children;
children.style.color = "red";

If there are more parent elements having same class then we can use querySelectorAll and forEach

HTML

<div class="parent">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
</div>
<div class="parent">
  <div>7</div>
  <div>8</div>
  <div>9</div>
</div>

JS

let children = document.querySelectorAll(".parent").children;
children.forEach(child => {
  child.style.color = "red";
})

While this can be done in one line with JQuery, I am assuming you are not using JQuery - in which case, your code will be:

var nodes = document.getElementById('ID_of_parent').childNodes;
for(var i=0; i<nodes.length; i++) {
    if (nodes[i].nodeName.toLowerCase() == 'div') {
         nodes[i].style.background = color;
     }
}

See http://jsfiddle.net/SxPxN/ for a quick example I created - Click on "change 'em" to see it in action


Try to use below codes:

var nodes = document.getElementById('ID_of_parent').getElementsByTagName("div");
for(var i=0; i<nodes.length; i++) {
    nodes[i].style.background = color;
}

var children = document.getElementById("div").children;

for (let i = 0; i < children.length; i++) {
  children[i].style.visibility = "hidden";
}

I am creating a variable called children and in it I am getting the element with the id "div" and then using .children to select the children and put it into an array. Then I create var i and use a for loop to go through and change all of their CSS value. The program stops after it has gone through each of the child elements.

Tags:

Javascript