简体   繁体   English

使用getElementById查找子元素

[英]Using getElementById to find child element

In Javascript, I need to select child elements with getElementById() : 在Javascript中,我需要使用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() ,它接受css选择器并返回元素列表,

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

would return an array of <a> elements which are descendants of <li> elements, in turn descendants of #topbarsection . 将返回的数组<a>元件,其后代<li>元素,在转弯后代#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. 是找到的第一个元素, [1]是第二个,依此类推。

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: 假设我们要将所有target属性设置为"_blank" ,我们可以使用for循环来实现:

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 ,它与document.getElementById相似,只返回一个元素。

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

It returns the first element matched. 它返回匹配的第一个元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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