querySelectorAll()
<html>
<head>
</head>
<body>
<h1>Seven wonders of the world</h1>
<p>Do you know the seven wonders of the world?</p>
<div id="content">
<h2>Wonders from Antiquity</h2>
<p>This list comes to us from ancient times.</p>
<ul class="wonders" id="ancient">
<li class="exists">Great Pyramid of Giza</li>
<li>Hanging Gardens of Babylon</li>
<li>Lighthouse of Alexandria</li>
<li>Statue of Zeus at Olympia</li>
<li>Temple of Artemis at Ephesus</li>
<li>Mausoleum at Halicarnassus</li>
<li>Colossus of Rhodes</li>
</ul>
<h2>Modern wonders of the world</h2>
<p>This list was decided by vote.</p>
<ul class="wonders" id="new">
<li class="exists">Petra</li>
<li class="exists">Great Wall of China</li>
<Li class="exists">Christ the Redeemer</Li>
<Li class="exists">Machu Picchu</Li>
<li class="exists">Chichen Itza</li>
<li class="exists">Colosseum</li>
<li class="exists">Taj Mahal</li>
</ul>
<h2>References</h2>
<ul>
<li><a href="https://en.wikipedia.org/wiki/Seven_Wonders_of_the_Ancient_World">Seven Wonders of the Ancient World</a></li>
<li><a href="https://en.wikipedia.org/wiki/New7Wonders_of_the_World">New Wonders of the World</a></li>
</ul>
</div>
</body>
</html>
// All paragraphs
console.log(document.querySelectorAll("p").length); // 3
// All paragraphs inside the "content" ID block
console.log(document.querySelectorAll("#content p").length); // 2
// All elements with the "exists" class
console.log(document.querySelectorAll(".exists").length); // 8
// All "ancient" wonders that still exist
console.log(document.querySelectorAll("#ancient > .exists").length); // 1
querySelector()
这个方法和上一种方法一样,只是这个方法只返回第一个匹配的元素,如果没找到关联的元素就返回 null。
// Show the first paragraph
console.log(document.querySelector("p").innerHTML);
几种选择元素的方法的对比
获取的元素数目 | 选择标准 | 方法名称 |
---|---|---|
多个 | 按标签(tag) | getElementsByTagName() |
多个 | 按 class | getElementsByClassName() |
多个 | 不按标签也不按 class | querySelectorAll() |
只有一个 | 按 ID | getElementById() |
只有一个(第一个) | 不按 ID | querySelector() |