getElementsByTagName
שיעור 7 מתוך 13 בקורס שיטות DOM ב-JavaScript של Coddy.
הפונקציה 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>כל השיעורים ביחידה שיטות DOM ב-JavaScript
תרגלו בעצמכם: Web אונליין