JavaScript/尋找元素/練習
外觀
< JavaScript | 尋找元素
主題:定位元素和 DOM 導航
我們使用以下 HTML 頁面進行練習。
<!DOCTYPE html>
<html>
<head>
<script>
function show() {
"use strict";
// ...
}
</script>
<style>
.head_2 {
display: flex;
justify-content: center;
}
.text, .text_right{
padding-left: 1em;
font-size: 1.4em;
}
.text_right {
display: flex;
justify-content: right;
padding-right: 1em;
}
.button {
height:1.4em;
width: 4em;
margin-top: 1em;
font-size: 1.2em;
background-color: Aqua;
}
</style>
</head>
<body>
<h1>An HTML header</h1>
<h2 class="head_2">An HTML sub-header</h2>
<div id="div_1">
<p id="p1" class="text">Paragraph 1</p>
<ul>
<li id="one">First item</li>
<li id="two">Second item</li>
<li id="three">Third item</li>
</ul>
<p id="p2" class="text">Paragraph 2</p>
<p id="p3" class="text_right">Paragraph 3</p>
</div>
<div id="div_2">
<p id="p4" class="text_right">Paragraph 4</p>
</div>
<button class="button" onclick="show()">Go</button>
</body>
</html>
1. 擴充套件函式 show,以顯示所有 li 元素的內容。
單擊以檢視解決方案
function show() {
"use strict";
const elemArray = document.getElementsByTagName("li");
for (let i = 0; i < elemArray.length; i++) {
alert(elemArray[i].innerHTML);
}
}
2. 擴充套件函式 show,以顯示 CSS 類 text 的所有元素的內容。
單擊以檢視解決方案
function show() {
"use strict";
const elemArray = document.getElementsByClassName("text");
for (let i = 0; i < elemArray.length; i++) {
alert(elemArray[i].innerHTML);
}
// please note that the third paragraph is not included
}
3. 擴充套件函式 show,以顯示第二個段落的內容。僅使用 getElementsByTagName。
單擊以檢視解決方案
function show() {
"use strict";
// retrieve all 'div'
const divArray = document.getElementsByTagName("div");
const firstDiv = divArray[0];
// navigate again, starting from the first 'div' element
const pArray = firstDiv.getElementsByTagName("p");
// show the second 'p' element
alert(pArray[1].innerHTML);
}