[英]Immediate nested DOM declaration in javascript
How can I get a nested DOM element in javascript instead of using jQuery? 如何在JavaScript中而不是使用jQuery获得嵌套的DOM元素? Example:
例:
$('#id') = document.getElementById('id');
I would like to convert this jQuery selector $('.nav > li')
to javascript. 我想将此jQuery选择器
$('.nav > li')
为javascript。 How can I do that? 我怎样才能做到这一点?
You have a really nice function called document.querySelectorAll()
which can select elements with css queries. 您有一个非常不错的函数,名为
document.querySelectorAll()
,可以使用CSS查询选择元素。
document.querySelectorAll('.nav > li');
If you plan to use it more than once, you can also use a var so it'll feel like using jQuery 如果您打算多次使用它,那么您也可以使用var,这样就可以像使用jQuery
var _ = document.querySelectorAll.bind(document)
var menuItems = _('.nav > li');
Just to complement the answers suggesting querySelectorAll
, here's how you would achieve that with old school DOM operations. 只是为了补充建议
querySelectorAll
的答案,这是使用旧式DOM操作将如何实现的方法。
var selected = [];
// get all elements that have the class 'nav' (.nav)
var navs = document.getElementsByClassName('nav');
var i, j, children;
// iterate over each nav and get a list of their direct children (.nav >)
for(i = 0; i < navs.length; i++) {
children = navs[i].children;
// iterate over the children and select if the tag is li (.nav > li)
for(j = 0; j < children.length; j++) {
if(children[j].tagName === 'LI') {
selected.push(children[j]);
}
}
}
Also serves as a good example of why declarative programming is better suited to this kind of task. 也可以作为说明性编程为什么更适合此类任务的一个很好的例子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.