getElementsByTagName
Lekcja 7 z 13 w kursie Metody DOM w JavaScript w Coddy.
Funkcja getElementsByTagName() zwraca tablicę wszystkich elementów o pasującej nazwie tagu HTML (np. div, p, span), umożliwiając wybieranie określonych typów elementów na całej stronie. Działa dokładnie tak samo jak funkcja getElementsByClassName().
const paragraphs = document.getElementsByTagName("p");W ten sposób możemy pobrać wszystkie tagi p do zmiennej paragraphs. Aby wprowadzić zmiany we wszystkich akapitach, musimy iterować po tej zmiennej.
Wyzwanie
ŁatwyOtrzymujesz kod HTML.
Używając wyłącznie JavaScript, zmodyfikuj wszystkie akapity tak, aby zawierały tekst “Updated text”.
Spróbuj swoich sił
<!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>Wszystkie lekcje w sekcji Metody DOM w JavaScript
2Metody DOM I
getElementByIdModyfikowanie stylu elementugetElementsByClassNameIterowanie i manipulowaniegetElementsByTagNamequerySelectorPoćwicz samodzielnie: Edytor online Web