0

How can I add an event to only the main container and to it's second child elements? In this case, it's id="container" and all class="secondChild"

What I current do add a listener to all elements inside the div

ele = document.getElementById('container');
ele.addEventListener('mousedown',myFunction)

<div class="main" id="container">
    <div class="firstChild">
        <div class="secondChild">
            <div class="inner">
                <div class="innerOne">This is Element 1</div>
                <div class="innerTwo">This is Element 2</div>
            </div>
        </div>
        <div class="secondChild">
            <div class="inner">
                <div class="innerOne">This is Element 3</div>
                <div class="innerTwo">This is Element 4</div>
            </div>
        </div>
        <div class="secondChild">
            <div class="inner">
                <div class="innerOne">This is Element 5</div>
                <div class="innerTwo">This is Element 6</div>
            </div>
        </div>
    </div>
</div>
ADyson
  • 44,946
  • 12
  • 41
  • 55
jmenezes
  • 1,810
  • 6
  • 24
  • 42

1 Answers1

0

You can go with Event Delegation:

From: https://www.sitepoint.com/javascript-event-delegation-is-easier-than-you-think/

Event delegation makes use of two often overlooked features of JavaScript events: event bubbling and the target element. When an event is triggered on an element, for example a mouse click on a button, the same event is also triggered on all of that element’s ancestors. This process is known as event bubbling; the event bubbles up from the originating element to the top of the DOM tree. The target element of any event is the originating element, the button in our example, and is stored in a property of the event object. Using event delegation it’s possible to add an event handler to an element, wait for an event to bubble up from a child element and easily determine from which element the event originated.

So you attach the listener to #container (you can attach it any ancestor), and the check for the event's target class (or whatever other property you want)

document.getElementById('container').addEventListener('event-name', ev => {

    switch(ev.target.className) {
        case 'inner':
        case 'innerOne':
        case 'innerTwo':
            // do something?
            break;
    }

});

(or maybe change the class to secondChild, I actually didn't quite get what element's were you trying to attach handlers to. Also sorry for my english)

Emilio Grisolía
  • 1,092
  • 1
  • 9
  • 13