Reputation:
I want to get every single ID of every element inside of a Div at once, and change all of their class names. Like:
<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?
Upvotes: 4
Views: 18794
Reputation: 73251
You can use querySelectorAll for the Child elements within 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
}
Upvotes: 0
Reputation: 91806
You can leverage querySelectorAll
to provide a selector to fetch the elements you are interested in.
var c = document.querySelectorAll("#container > div");
console.log(c); // array of all children div below #container
Upvotes: 0
Reputation: 44714
Leverage document.querySelectorAll()
and a loop to achieve what you're looking for:
var everyChild = document.querySelectorAll("#container div");
for (var i = 0; i<everyChild.length; i++) {
everyChild[i].classList.add("anything");
}
Upvotes: 3
Reputation: 4233
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);
Upvotes: 6