getElementsByTagName
Bài học 7 trên 13 trong khóa học Các phương thức DOM trong JavaScript của Coddy.
Hàm (function) getElementsByTagName() trả về một mảng (array) gồm tất cả phần tử có tên thẻ HTML khớp (ví dụ: div, p, span), giúp bạn chọn các loại phần tử cụ thể trên toàn trang. Hàm này hoạt động giống hệt hàm getElementsByClassName().
const paragraphs = document.getElementsByTagName("p");Đây là cách chúng ta có thể lấy tất cả thẻ p vào biến paragraphs. Để thay đổi tất cả đoạn văn, chúng ta cần lặp qua biến này.
Thử thách
DễBạn có một đoạn code HTML.
Chỉ sử dụng JavaScript, hãy sửa đổi tất cả các đoạn văn để chúng chứa văn bản “Updated text”.
Tự làm thử
<!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>Tất cả bài học trong Các phương thức DOM trong JavaScript
2Phương thức DOM I
getElementByIdChỉnh sửa kiểu dáng phần tửgetElementsByClassNameDuyệt qua và thao tácgetElementsByTagNamequerySelector3Các phương thức DOM II
querySelectorAlladdEventListenerinnerHTMLcreateElement và appendChildChuyển đổi classListTự luyện tập: Playground Web