I need a clarification of targeting an element from the markup

50 Views Asked by At

I am following a class online and the tutor target a <button> document in which I don't really understand how he did it because he used a document.querySelector to target the parent and that's all.

<div class="row">
    <form id="task-form" action="index.php">
        <div class="input-field col s12">
            <input type="text" name="task" id="task" value="">
            <label for="task">New Task</label>
        </div>
    </div>
    <button id="add" class="btn">Add</button>
</form>

he then wrote :

document.querySelector('form').addEventListener('submit', function(event) { /* ... */ })

to me what I understand is that the querySelector will only select the firstChild in this case.

2

There are 2 best solutions below

1
Danny On

The code just targets the <form> and adds a listener for the submit event.
It is not targeting any <button>.

1
Ath.Bar. On

He actually doesn't add listeners to any button. What you confused was the <form> having an onsubmit event listener. Since there is only one button in the form, its type attribute is automatically set to submit, making it trigger the form.onsubmit event every time.

Also, the code is a bit wrong. You open a div, a form, and before closing the form, you close the div. If that was made by the person who runs the course, I would recommend to stop watching that course in general, since it can confuse a lot...