简体   繁体   中英

Immediate nested DOM declaration in javascript

How can I get a nested DOM element in javascript instead of using jQuery? Example:

$('#id') = document.getElementById('id');

I would like to convert this jQuery selector $('.nav > li') to javascript. How can I do that?

You have a really nice function called document.querySelectorAll() which can select elements with css queries.

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 _ = 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.

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.

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.

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