getElementsByTagName
Lesson 7 of 13 in Coddy's JavaScript DOM Methods course.
The function getElementsByTagName() returns an array of all elements with a matching HTML tag name (e.g., div, p, span), allowing you to target specific types of elements across the page. This works exactly as the getElementsByClassName() function.
const paragraphs = document.getElementsByTagName("p");This is how we can retrieve all p tags in paragraphs variable. To make changes to all paragraphs, we have to iterate over this variable.
Challenge
EasyYou are given HTML code.
Using JavaScript only, modify all the paragraphs to hold the text “Updated text”.
Try it yourself
<!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>All lessons in JavaScript DOM Methods
2DOM Methods I
getElementByIdModify Element StylegetElementsByClassNameLoop Through and ManipulategetElementsByTagNamequerySelector