更多例子
获取<div>元素内的所有<p>元素,并设置第一个<p>元素(索引0)的背景颜色:
// Get the element with id="myDIV" (a div), then get all p elements inside div
var x = document.getElementById("myDIV").querySelectorAll("p");
// Set the background color of the first <p> element (index 0) in div
x[0].style.backgroundColor = "red";
尝试一下
使用class =“example”获取<div>中的所有<p>元素,并设置第一个<p>元素的背景:
// Get the element with id="myDIV" (a div), then get all p elements with class="example" inside div
var x = document.getElementById("myDIV").querySelectorAll("p.example");
// Set the background color of the first <p> element with class="example" (index 0) in div
x[0].style.backgroundColor = "red";
尝试一下
找出在<div>元素中使用class=“example”的元素数量(使用NodeList对象的length属性):
/* Get the element with id="myDIV" (a div), then get all p elements with class="example" inside div, and return the number of elements found */
var x = document.getElementById("myDIV").querySelectorAll(".example").length;
尝试一下
在<div>元素中使用class =“example”设置所有元素的背景颜色:
// Get the element with id="myDIV" (a div), then get all elements with class="example" inside div
var x = document.getElementById("myDIV").querySelectorAll(".example");
// Create a for loop and set the background color of all elements with class="example" in div
var i;
for (i = 0; i < x.length; i++) {
x[i].style.backgroundColor = "red";
}
尝试一下
设置<div>元素中所有<p>元素的背景颜色:
// Get the element with id="myDIV" (a div), then get all p elements inside div
var x = document.getElementById("myDIV").querySelectorAll("p");
// Create a for loop and set the background color of all p elements in div
var i;
for (i = 0; i < x.length; i++) {
x[i].style.backgroundColor = "red";
}
尝试一下
设置<div>元素中具有“target”属性的所有<a>元素的边框样式:
// Get the element with id="myDIV" (a div), then get all <a> elements with a "target" attribute inside div
var x = document.getElementById("myDIV").querySelectorAll("a[target]");
// Create a for loop and set the border of all <a> elements with a target attribute in div
var i;
for (i = 0; i < x.length; i++) {
x[i].style.border = "10px solid red";
}
尝试一下
设置<div>元素中所有<h2>,<div>和<span>元素的背景颜色:
// Get the element with id="myDIV" (a div), then get all <h2>, <div> and <span> elements inside <div>
var x = document.getElementById("myDIV").querySelectorAll("h2, div, span");
// Create a for loop and set the background color of all <h2>, <div> and <span> elements in <div>
var i;
for (i = 0; i < x.length; i++) {
x[i].style.backgroundColor = "red";
}
尝试一下