JavaScript JavaScript and the DOM Responding to User Interaction Event Delegation

Dimitris Karatsoulas
Dimitris Karatsoulas
5,724 Points

Why do we use "document.getElementsByTagName('section')[0]"?

So, what I can't understand is why we use [0] at the end of the ('section'). I have tried to delete it and the code doesn't work. Since we have just one section tag why is the [0] that indicates the first object of an array necessary? Wouldn't that be more suitable if we had 2 or more <section> tags?

app.js
let section = document.getElementsByTagName('section')[0];

section.addEventListener('click', (e) => {
  if (e.target.tagName === "INPUT"){
  e.target.style.backgroundColor = 'rgb(255, 255, 0)';
  }

});
index.html
<!DOCTYPE html>
<html>
    <head>
        <title>JavaScript and the DOM</title>
    </head>
    <link rel="stylesheet" href="style.css" />
    <body>
        <section>
            <h1>Making a Webpage Interactive</h1>
            <p>JavaScript is an exciting language that you can use to power web servers, create desktop programs, and even control robots. But JavaScript got its start in the browser way back in 1995.</p>
            <hr>
            <p>Things to Learn</p>
            <ul>
                <li>Item One: <input type="text"></li>
                <li>Item Two: <input type="text"></li>
                <li>Item Three: <input type="text"></li>
                <li>Item Four: <input type="text"></li>
            </ul>
            <button>Save</button>
        </section>
        <script src="app.js"></script>
    </body>
</html>

2 Answers

KRIS NIKOLAISEN
KRIS NIKOLAISEN
52,824 Points

getElementsByTagName returns an HTMLCollection regardless of how many elements are found. If 0 then the collection is empty. If one or more then the first item will have an index equal to 0.

Dimitris Karatsoulas
Dimitris Karatsoulas
5,724 Points

Thank you for your reply. So, when we use getElementsByTagName we always have to target the items of the HTML collection, either by a [index] or a for loop.