使用getElementById查找子元素

时间:2015-01-11 15:15:48

标签: javascript html css

在Javascript中,我需要选择getElementById()的子元素:

#topbarsection li a {}

我试过这个:

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

和此:

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

2 个答案:

答案 0 :(得分:4)

你应该使用querySelectorAll来做这些事情:

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

答案 1 :(得分:1)

通常,人们会使用document.querySelectorAll(),它接受​​css选择器并返回元素列表,

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

会返回一个<a>元素数组,这些元素是<li>#topbarsection个元素,依次为document.querySelectorAll('#topbarsection li a')[0] 的后代。

您可以像使用普通数组一样访问元素

[1]

是否找到第一个元素,target是第二个元素等等。

因此,我们可以依次对每个元素应用更改;假设我们要将所有"_blank"属性设置为var elems = document.querySelectorAll('#topbarsection li a'); for (var i = 0, l = elems.length; i < l; i++) { elems[i].setAttribute("target", "_blank"); } ,我们可以使用for循环执行此操作:

document.getElementById

Ta - da!

还有不太常用的descendants,它与document.querySelector('.header') === document.querySelectorAll('.header')[0] 的工作方式类似,因为它只返回一个元素。

{{1}}

返回匹配的第一个元素。

相关问题