简体   繁体   English

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

[英]How to get ALL id's inside of a DIV using pure javascript

I want to get every single ID of every element inside of a Div at once, and change all of their class names. 我想立刻获取Div中每个元素的每个ID,并更改所有类名。 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? 我已经看过使用库的解决方案,但这可能与纯Javascript一起使用吗?

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

Leverage document.querySelectorAll() and a loop to achieve what you're looking for: 利用document.querySelectorAll()和循环来实现您的目标:

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

JSFiddle 的jsfiddle

You can use querySelectorAll for the Child elements within the specified parent: 您可以将querySelectorAll用于指定父级中的Child元素:

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
}

You can leverage querySelectorAll to provide a selector to fetch the elements you are interested in. 您可以利用querySelectorAll提供选择器来获取您感兴趣的元素。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM