-2

So i have started some javascript and i wanted to ask that is there a way to select elements in an array. I read the querySelector, querySelectorAll and getElementsByClassName but these select the entire array but not the elements in it. Because i want to add event listener to elements so that delete button removes the list item. If my code is like this:-

    <body>
    <h3>Simple Add/Remove Task</h3>
    <h4>To do List</h4>
    <ul>
        <div>
            <li>Wake up</li>
            <li>Study</li>
        </div>

    <div>
        <button>Delete</button><br>
        <button>Delete</button>
    </div>
    </ul>

    <script type="text/javascript" src="./script.js"></script>
</body>
new2coding
  • 27
  • 1
  • 7
  • 1
    You can not assign an event handler to multiple elements in one go, you have to do that for each one separately. So you will need to _loop over_ your selected elements. An alternative to adding an individual event handler to all elements, is to use _event delegation_. – CBroe Jul 13 '20 at 11:52
  • How do loop through the list? – new2coding Jul 13 '20 at 11:58
  • https://stackoverflow.com/questions/157260/whats-the-best-way-to-loop-through-a-set-of-elements-in-javascript – CBroe Jul 13 '20 at 12:00

1 Answers1

0

Well... What do you want to select here? In HTML, there is no such thing as an Array.

Suppose you want to add an event listener to your first button. As there is really no single feature distinguishing the two Delete buttons, you want to add some sort of identifier to them. For example:

<button id="btn-1">Delete</button><br>
<button id="btn-2">Delete</button>

You are then able to select the first button like this:

button1 = document.getElementById("btn-1");

...or, with more modern JavaScript (but less browser compatible):

button1 = document.querySelector("#btn-1");
Dominik Weitz
  • 120
  • 1
  • 7
  • i want to select li in ul using javascript. what i am trying to do is select all li and then remove them by the delete button – new2coding Jul 13 '20 at 12:08