简体   繁体   中英

Using getElementById to find child element

In Javascript, I need to select child elements with getElementById() :

#topbarsection li a {}

I've tried this:

topbarsection = document.getElementById('topbarsection>li>a');

and this:

topbarsection = document.getElementById('topbarsection li a');

您应该将querySelectorAll用于此类事情:

document.querySelectorAll('#topbarsection > li > a');

Normally, one would use document.querySelectorAll() , it accepts css selectors and returns a list of elements,

document.querySelectorAll('#topbarsection li a');

would return an array of <a> elements which are descendants of <li> elements, in turn descendants of #topbarsection .

You can access the elements as you would the items a normal array,

document.querySelectorAll('#topbarsection li a')[0]

Is the first element found, [1] the second, etc.

Because of this, we can apply changes to each of the elements in turn; let's say we want to set all their target attributes to "_blank" , we can do that using a for loop:

var elems = document.querySelectorAll('#topbarsection li a');

for (var i = 0, l = elems.length; i < l; i++) {
    elems[i].setAttribute("target", "_blank");
}

Ta - da!

There is also the less commonly used document.querySelector , which works similarly to document.getElementById in that it only returns a single element.

document.querySelector('.header') === document.querySelectorAll('.header')[0]

It returns the first element matched.

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