Javascript event parent element

How JavaScript Event Delegation Works

One of the hot methodologies in the JavaScript world is event delegation, and for good reason. Event delegation allows you to avoid adding event listeners to specific nodes; instead, the event listener is added to one parent. That event listener analyzes bubbled events to find a match on child elements. The base concept is fairly simple but many people don’t understand just how event delegation works. Let me explain the how event delegation works and provide pure JavaScript example of basic event delegation.

Let’s say that we have a parent UL element with several child elements:

Let’s also say that something needs to happen when each child element is clicked. You could add a separate event listener to each individual LI element, but what if LI elements are frequently added and removed from the list? Adding and removing event listeners would be a nightmare, especially if addition and removal code is in different places within your app. The better solution is to add an event listener to the parent UL element. But if you add the event listener to the parent, how will you know which element was clicked?

Simple: when the event bubbles up to the UL element, you check the event object’s target property to gain a reference to the actual clicked node. Here’s a very basic JavaScript snippet which illustrates event delegation:

// Get the element, add a click listener. document.getElementById("parent-list").addEventListener("click", function(e) < // e.target is the clicked element! // If it was a list item if(e.target && e.target.nodeName == "LI") < // List item found! Output the ID! console.log("List item ", e.target.id.replace("post-", ""), " was clicked!"); >>);

Start by adding a click event listener to the parent element. When the event listener is triggered, check the event element to ensure it’s the type of element to react to. If it is an LI element, boom: we have what we need! If it’s not an element that we want, the event can be ignored. This example is pretty simple — UL and LI is a straight-forward comparison. Let’s try something more difficult. Let’s have a parent DIV with many children but all we care about is an A tag with the classA CSS class:

// Get the parent DIV, add click listener. document.getElementById("myDiv").addEventListener("click",function(e) < // e.target was the clicked element if (e.target && e.target.matches("a.classA")) < console.log("Anchor element clicked!"); >>);

Using the Element.matches API, we can see if the element matches our desired target.

Читайте также:  Найдите сумму цифр заданного натурального числа питон рекурсия

Since most developers use a JavaScript library for their DOM element and event handling, I recommend using the library’s method of event delegation, as they are capable of advanced delegation and element identification.

Hopefully this helps you visually the concept behind event delegation and convinces you of delegation’s power!

Recent Features

CSS 3D Folding Animation

CSS 3D Folding Animation

CSS vs. JS Animation: Which is Faster?

CSS vs. JS Animation: Which is Faster?

Incredible Demos

Upload Photos to Flickr with PHP

Upload Photos to Flickr with PHP

MooTools ContextMenu Plugin

MooTools ContextMenu Plugin

Discussion

e.target.className.split(" ").indexOf(class) !=-1

Instead of the loop. I know it is not supported everywhere but everyone with addEventListener supports indexOf

The availability of Array.indexOf is independent of any one method or nodeList , it is dependent on the browser you are using and the version of JavaScript it implements. Firefox has had indexOf for some time now, so to with later version of Google Chrome.

var re = new RegExp('\\b'+class+'\\b'); re.test(e.target.className);
event.target && event.target.nodeName == "A" && event.target.classList.contains("myClass")

If A has a className elementABC ,but what we want to find really is class elementA , in this case, use indexOf(‘elementA’) is not correct

Good concept. When dealing with dynamic content that needed events, I typically loaded with a rel set to “untouched”, or without one at all and load a function that would look for all untouched methods or without the “touched” rel, give them the correct event, and set their rel ‘s to “touched”. Is there a performance improvement done by using your method?

Depends on what you’re doing. It occurs to me, however, that you may need to run the event routine multiple times if you ever add elements dynamically. The rel tag solution, if you only want to do something once, isn’t a bad idea. Elitists would tell you to use data-[whateverAttributeName].

var classes = e.target.className.split(" "); // Search for the CSS class! if(classes) < //. >

When className returns an empty string, split should return an array containing one empty string, which evaluates to true in an if statement. Otherwise split will return the split elements or an array with the original string. That being said, is if (classes) cautionary, is it directed at a known browser, is it unnecessary, or am I missing a case where the if would be false? I can’t blame one for being cautious especially with browser reputation being what it is and can’t rule out that I’m missing something!

I’m an experienced programmer, but relatively new to javascript, but not new to GUI programming (Windows, Swing, Android, etc.). I read a lot about the importance of event delegation, but I’m skeptical. To me, it seems like it’s a venerated “best practice” that’s no longer relevant. I just can’t believe that modern computers and browsers are affected by the very marginal gains (?) offered by event delegation. What exactly *are* the benefits? From a coding style perspective, event delegation shows odd cohesion.When coding event handling in other environments (like desktop, etc.) one normally doesn’t have a central event handler with an embedded case structure to test what was clicked. Especially with the common handler tied to some UI implementation which could very well change as users ask for changes to the UI. User: “Please move that button on the toolbar.” Of course, event handlers on the individual items would mean such changes are not problematic. The author says “what if LI elements are frequently added and removed from the list? Adding and removing event listeners would be a nightmare.” Ok, for *semantically* grouped items, like items in a list, I can see it (just like you’d have a single event handler for a combo box, and not on the items in the box). So… Is this some venerated yet anachronistic style, or are there any statistics or tests I can run that show the benefits.

There are indeed direct benefits. In standard application programming, one may deal more directly with the garbage collector or at least have a better conception of how the GC operates. In web development, the GC is completely variable per user agent — you have literally no idea how or when it will operate because each user may potentially use a different agent. Imagine a use case where you have a grid of several hundred dynamically generated table cells (think an hour-by-hour availability calendar): attaching an event to each of these cells would, for starters, take a moment. While you’re looping over them, the browser UI thread is locked and the user perceives bad performance. You also wind up with several hundred listeners, and depending on your script architecture that could also mean several hundred function references. This is in itself weighty… but now the user switches dates and you have a new batch of cells injected into the table. Do you loop the old cells and remove the listener from each? That will take time, then you have to loop again to apply the new listeners. Do you just ignore the old and only worry about the new? Now you have several hundred references sitting in memory, waiting for the mythical GC that will fire who-knows-when. Plus, you may have created circular references and those listeners will never leave memory, *even when the user navigates to a completely different page*. Your function references are still sitting in memory, too. That is one quite feasible use-case where a single event listener and delegation eliminates all those references and concerns. In your toolbar button example, the delegating event would be attached to the toolbar itself. This pattern actually compliments a more flexible UI; you don’t think about the event, you just move the button. Or add a new one. Or delete one. No matter what change takes place, the single event listener will bubble up any actions. I don’t think the cohesion is odd at all — one would use delegate events to apply an action to a specific group of elements. Cohesion already existed; these buttons are toolbar buttons, and when you click on, a centralized handler will determine what happens. This is how you already code (presumably), the real differences is that without delegation, you have more references to keep track of. Delegation makes most sense when it is used with mutually cohesive elements: LI s in a UL , TR s in a TABLE , etc. Control icons and the like are also another common use, though they aren’t semantically grouped they still have an underlying cohesion whether you used delegation or not.

This is a really great explanation. Thank you for shedding more light on the gains. I had already begun adopting delegation just for the sake of avoiding the need to replace event handlers on dynamic elements, but the discussion of performance implications was really enlightening. Cheers!

Источник

Javascript event parent element

Last updated: Jan 12, 2023
Reading time · 2 min

banner

# Get the ID of a Parent element on Click using JavaScript

To get the id of the parent element on click:

  1. Add a click event listener to the element.
  2. Use the event.target property to get the element the user clicked on.
  3. Use the parentElement property to get the parent and access its id property.

Here is the HTML for the examples.

Copied!
DOCTYPE html> html lang="en"> head> title>bobbyhadz.comtitle> meta charset="UTF-8" /> head> body> div id="parent"> p id="child" style="background-color: salmon; width: 100px; height: 100px" > Child 1 p> div> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const child = document.getElementById('child'); child.addEventListener('click', function handleClick(event) // 👇️ "parent" console.log(event.target.parentElement.id); >);

If you load the page and click on the child element, you will see the string parent logged to the console.

We added a click event listener to the child element.

Every time the element is clicked, the handleClick function is invoked.

We used the target property on the event object to access the parent element.

The target property is a reference to the object (element) on which the event was dispatched.

Источник

Оцените статью