Menu
Coddy logo textTech

getElementsByTagName

Coddyの「JavaScript DOM メソッド」コースのレッスン 7/13。

getElementsByTagName() 関数は、一致する HTMLタグ名(例:divpspan)を持つすべての要素の配列を返し、ページ全体の特定のタイプの要素をターゲットにすることができます。これは getElementsByClassName() 関数とまったく同じように動作します。

const paragraphs = document.getElementsByTagName("p");

これが、paragraphs 変数にすべての p タグを取得する方法です。すべての段落に変更を加えるには、この変数を反復処理する必要があります。

challenge icon

チャレンジ

簡単

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 メソッドのすべてのレッスン