I have this html code,
<div id=menu>
<div class=other></div>
<div class=select></div>
<div class=select></div>
</div>
how can I select all div that have classname of "select" and add it to an array?
I tried this code but not do what I expected,
var arr = document.getElementById('menu').children;
for(int i=0;i<arr.length;i++){
if(arr[i].className=='select'){
//do following
}
}
You can use document.getElementsByClassName(classname)
as such:
selectdivs = document.getElementsByClassName('select')
Since the function returns a list.
Or, you could create a blank list and push the valid div
s:
all = []
for(var i = 0;i < document.getElementById("menu").children.length;i++){
div=document.getElementById("menu").children[i];
if(div.className == "select"){
all.push(div)
}
}
You can use another array to store required elements:
var arr = document.getElementById('menu').children;
var eleArray = [];
for(int i=0;i<arr.length;i++){
if(arr[i].className=='select'){
eleArray.push(arr[i]);
}
}
If it's needless to find for the children of menu
, you can directly use document.getElementsByClassName('select')
which returns an array of all the elements with class select
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.