How to get ALL ID inside a DIV using pure javascript

I want to get every id of every element inside a Div at once and change all their class names. How:

<div id = "container">
    <div id = "alot"></div>
    <div id = "of"></div>
    <div id = "random"></div>
    <div id = "ids"></div>
</div>

<script>
    var everyId = //all of the ids in #container. but how ?
    document.getElementById( everyId ).className = "anything";
</script>

      

I've seen solutions using libraries, but is this possible with pure Javascript?

+3


source to share


4 answers


Leverage document.querySelectorAll()

and cycle to achieve what you are looking for:

var everyChild = document.querySelectorAll("#container div");
for (var i = 0; i<everyChild.length; i++) {
    everyChild[i].classList.add("anything");
}

      



JSFiddle

+2


source


Try something like this:



var ids = [];
var children = document.getElementById("container").children; //get container element children.
for (var i = 0, len = children.length ; i < len; i++) {
    children[i].className = 'new-class'; //change child class name.
    ids.push(children[i].id); //get child id.
}

console.log(ids);

      

+3


source


You can use querySelectorAll on children in the specified parent:

var a = document.querySelectorAll('#container > div'); // get all children within container
console.log(a);
for (var i = 0; i<a.length; i++){ // loop over the elements
    console.log(a[i].id);  //  get the ids
    a[i].className = 'newClass';  // change the class names
}

      

0


source


You can use querySelectorAll

to provide the selector with a selection of elements of interest.

var c = document.querySelectorAll("#container > div");
console.log(c);  // array of all children div below #container

      

0


source







All Articles