Skip to content
Advertisement

Attach event not working when click on child

I have some dynamically added elements. I want to attach ‘click’ event on a specific class. But the problem is if I click on the child element it’s not working. Here is my dynamically added elements.

<div id="steps">    
    <div class="step">
        <a class="btn step-del">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><path d="M12.277 3.763a.9.9 0 010 1.273L9.293 8.018l2.984 2.986a.9.9 0 01-1.273 1.272L8.02 9.291l-2.984 2.985a.9.9 0 01-1.273-1.272l2.984-2.986-2.984-2.982a.9.9 0 011.273-1.273L8.02 6.745l2.984-2.982a.9.9 0 011.273 0z"></path></svg>
        </a>

        Step 1
    </div>

    <div class="step">
        <a class="btn step-del">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><path d="M12.277 3.763a.9.9 0 010 1.273L9.293 8.018l2.984 2.986a.9.9 0 01-1.273 1.272L8.02 9.291l-2.984 2.985a.9.9 0 01-1.273-1.272l2.984-2.986-2.984-2.982a.9.9 0 011.273-1.273L8.02 6.745l2.984-2.982a.9.9 0 011.273 0z"></path></svg>
        </a>

        Step 2
    </div>
</div>

Here is my javascript code:

    document.body.addEventListener('click', function (evt) {

        if ( evt.target.classList.contains("step-del") ) {
            alert(this)
        }
    }, false);

Advertisement

Answer

Maybe the target is a child element of the “step-del”, so you need to check with closest, which will search for the parent elements if any of them has “step-del” class.

document.body.addEventListener('click', function (evt) {
        const del = evt.target.closest(".step-del")
        if (del) {
            alert(del)
        }
    }, false);
<div id="steps">    
    <div class="step">
        <a class="btn step-del">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><path d="M12.277 3.763a.9.9 0 010 1.273L9.293 8.018l2.984 2.986a.9.9 0 01-1.273 1.272L8.02 9.291l-2.984 2.985a.9.9 0 01-1.273-1.272l2.984-2.986-2.984-2.982a.9.9 0 011.273-1.273L8.02 6.745l2.984-2.982a.9.9 0 011.273 0z"></path></svg>
        </a>

        Step 1
    </div>

    <div class="step">
        <a class="btn step-del">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><path d="M12.277 3.763a.9.9 0 010 1.273L9.293 8.018l2.984 2.986a.9.9 0 01-1.273 1.272L8.02 9.291l-2.984 2.985a.9.9 0 01-1.273-1.272l2.984-2.986-2.984-2.982a.9.9 0 011.273-1.273L8.02 6.745l2.984-2.982a.9.9 0 011.273 0z"></path></svg>
        </a>

        Step 2
    </div>
</div>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement