[英]Create an array of a parents children in javascript
I am trying to create an array of a parent div's ( id="lol"
) children and them fetch them to change display:none;
我正在尝试创建父div( id="lol"
)子级的数组,它们获取它们以更改display:none;
except for the child with id="a"
. 除了id="a"
的孩子。 I've tried this but it doesn't work. 我已经尝试过了,但是没有用。 How can I improve this to get it to work? 我如何改进它才能使其正常工作?
function myFunction() {
var x = document.getElementById('a');
var children = [].slice.call(document.getElementById('lol').getElementsByTagName('*'),0);
var arrayLength = children.length;
for (var i = 0; i < arrayLength; i++) {
var name = children[i].getAttribute('id');
var z = document.getElementById(name);
z.style.display = 'none';
}
x.style.display = 'block';
}
If every child has an id
attribute than it will work. 如果每个孩子都有一个id
属性,它将起作用。 Otherwise, some children might not have id
attribute, in that case variable z
will be undefined
and accessing style
property over z
which is undefined
will give error. 否则,有些孩子可能没有id
属性,在这种情况下,变量z
将undefined
和访问style
对财产z
这是undefined
会给错误。 Simple fix would be just handling undefined
variable: 简单的解决方法就是处理undefined
变量:
if(z)
z.style.display = 'none';
Same goes with variable x
, too. 变量x
也是如此。
How about using jQuery? 如何使用jQuery?
$('#lol').children(':not(#a)').hide();
If jQuery is not an option you can do this: 如果没有jQuery选项,则可以执行以下操作:
var lol = document.getElementById('lol');
var children = lol.querySelectorAll(':not(#a)');
for(var i=0;i<children.length;i++) {
children[i].style.display = 'none';
}
Even more "low-level": 更“低级”:
var lol = document.getElementById('lol');
var children = lol.childNodes;
for(var i=0;i<children.length;i++){
if(children[i].id != 'a') {
children[i].style.display = 'none';
}
}
function myFunction() {
var children = [].slice.call(document.getElementById('lol').getElementsByTagName('*'),0);
var arrayLength = children.length;
for (var i = 0; i < arrayLength; i++) {
children[i].style.display = 'none';
}
document.getElementById('a').style.display = 'block';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.