如何使用纯javascript在DIV中获取所有id

时间:2014-12-23 22:45:00

标签: javascript getelementbyid

我希望立即获取Div中每个元素的每个ID,并更改所有类名。像:

<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>

我已经看过使用库的解决方案,但纯粹的Javascript可以实现吗?

4 个答案:

答案 0 :(得分:4)

尝试这样的事情:

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);

答案 1 :(得分:3)

利用document.querySelectorAll()和循环来实现您所寻找的目标:

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

JSFiddle

答案 2 :(得分:0)

您可以将querySelectorAll用于指定父级中的子元素:

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
}

答案 3 :(得分:0)

您可以利用querySelectorAll提供一个选择器来获取您感兴趣的元素。

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