getElementsByTagName
Coddy JavaScript DOM 方法 课程的第 7 课,共 13 课。
函数 getElementsByTagName() 会返回所有匹配 HTML 标签名的元素组成的数组(例如,div、p、span),让你可以在整个页面中定位特定类型的元素。它的工作方式与 getElementsByClassName() 函数完全相同。
const paragraphs = document.getElementsByTagName("p");这样,我们就可以将所有 p 标签存入 paragraphs 变量中。要修改所有段落,我们需要遍历这个变量。
挑战
简单给你一段 HTML 代码。
只能使用 JavaScript,将所有段落的文本修改为 “Updated text”。
亲手试试
<!DOCTYPE html>
<html>
<body>
<h1>Welcome to Random HTML!</h1>
<p>This is a randomly generated HTML file. Here's a mix of different elements:</p>
<ul>
<li>This is an unordered list item.</li>
<li>This is another unordered list item.</li>
</ul>
<p>Below are the four randomly generated paragraphs:</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed aliquet ligula sit amet convallis sodales.</p>
<p>Nulla facilisi. Nulla eget metus vitae ligula aliquam rhoncus.</p>
<p>Maecenas feugiat ultricies nisi, id auctor purus laoreet at.</p>
<p>Curabitur vitae dictum arcu, ac fermentum ligula. Duis feugiat arcu non tincidunt posuere.</p>
<blockquote>
<p>This is a blockquote. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</blockquote>
<p>Thank you for exploring this random HTML file!</p>
<script src="script.js"></script>
</body>
</html>JavaScript DOM 方法中的所有课
自己练习: Web 在线编辑器