[英]Using getElementById to find child element
在Javascript中,我需要使用getElementById()
選擇子元素:
#topbarsection li a {}
我已經試過了:
topbarsection = document.getElementById('topbarsection>li>a');
和這個:
topbarsection = document.getElementById('topbarsection li a');
您應該將querySelectorAll
用於此類事情:
document.querySelectorAll('#topbarsection > li > a');
通常,將使用document.querySelectorAll()
,它接受css選擇器並返回元素列表,
document.querySelectorAll('#topbarsection li a');
將返回的數組<a>
元件,其后代的<li>
元素,在轉彎后代#topbarsection
。
您可以像訪問普通數組一樣訪問元素,
document.querySelectorAll('#topbarsection li a')[0]
是找到的第一個元素, [1]
是第二個,依此類推。
因此,我們可以依次將更改應用於每個元素。 假設我們要將所有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");
}
-!
還有一個不太常用的document.querySelector
,它與document.getElementById
相似,只返回一個元素。
document.querySelector('.header') === document.querySelectorAll('.header')[0]
它返回匹配的第一個元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.