示例HTML:
<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>
HTML 内容
使用 innerHTML 属性检索 DOM 元素的 HTML 内容。
操作如下:
// The HTML content of the DOM element with ID "content"
console.log(document.getElementById("content").innerHTML);
文本内容
使用 textContent 属性返回 DOM 元素的所有文本内容,不带任何 HTML 标记。
// The textual content of the DOM element with ID "content"
console.log(document.getElementById("content").textContent);
属性
getAttribute() 方法可以应用于 DOM 元素并将返回给定属性的值。
// Show href attribute of the first link
console.log(document.querySelector("a").getAttribute("href"));
一些属性可以直接访问,比如 id、href 和 value 属性。
// Show ID attribute of the first list
console.log(document.querySelector("ul").id);
// Show href attribute of the first link
console.log(document.querySelector("a").href);
可以使用 hasAttribute() 方法检查属性是否存在。
if (document.querySelector("a").hasAttribute("target")) {
console.log("The first link has a target attribute.");
} else {
console.log("The first link does not have a target attribute."); // Will be shown
}
获取 class
在网页中,一个标签可以有多个类。classList 属性检索 DOM 元素的 class 列表。
// List of classes of the element identified by "ancient"
const classes = document.getElementById("ancient").classList;
console.log(classes.length); // 1 (since the element only has one class)
console.log(classes[0]); // "wonders"
可以通过 contains() 方法测试元素的 classList 中是否有该类。
// Check whether "ancient" element contains the "wonders" class
console.log(String(document.getElementById("ancient").classList.contains('wonders')));