Event Listeners and Parent Nodes
One of the best ways to learn a language is to be okay with failing at it multiple times.
— me.
I am building a single page application with a Javascript frontend and a Ruby on Rails API backend. I found myself having the most trouble with attaching an event listener
to an element.
Javascript “listens” for events to happen. It listens to whether a page has resized or if a button was clicked. The most common event is a “click”. Another common event is “submit”, which would trigger form submission.
I wanted to attach an event to a delete button. In order to do this, an understanding of HTML nodes, or elements was needed.
The Parent Node
I wanted to attach an event listener to the delete button element, which is:
<input type=”submit” name=”delete” class="delete" value=”Delete Project”>
All I thought I needed to do was select the element, or node like this:
let deleteButton = document.getElementByClassName("delete")
and then attach the event listener, like so:
deleteButton.addEventListener("click", (event) => {
*insert necessary code here*
}
Well that didn’t work quite well. When I clicked the button nothing happened. Absolutely nothing. Nothing was triggered. Why? Well I‘d like to put it like this: I didn’t ask the parent node for permission.
The delete button element is a nested node, meaning it is a child node. What does a child have? A parent.
I needed the parent node, or parent element to gain access to the delete button. The parent node necessary here is:
<div class="div3" id="projects-container">
I needed to obtain “permission” to gain access, because the element I wanted to access was nested in all of this:
<div>
<ul>
<li>
<h2>
<h3>
<h3>
<h4>
<p>
<input>
</li>
</ul>
</div>
So I selected the the <div>
element, a.k.a parent node:
const projectParentNode = document.getElementById('projects-container')
then I attached an event listener to the selected parent node, like so:
projectParentNode.addEventListener('click', (event) => {
*insert important code here*
}
Now I have to “ask permission”:
projectParentNode.addEventListener('click', (event) => {
let deleteEvent = event.target.className // asking permission
if(deleteEvent === 'delete') { // still asking permission
*insert extremely triggering and important code here*
}
}
When I found the event was triggered and actual objects were deleting from the database, I was super excited. I made sure to make a note about how amazing parent nodes are.