-1

I'm looking for native JavaScript code for this example with jQuery:

$("#parent").on("click", ".child", function(){
    alert("clicked");
});

What I did so far works with the elements that come with the page but not the dynamically generated ones:

var children = document.getElementById("parent").getElementsByClassName("child");
for (var i = 0, l = children.length; i < l; i++)
{
    children[i].onclick = foo;
}
function foo(el)
{
    alert("child clicked");
}

How can I make this code work for the dynamically generated elements?

If you are looking for the answer, here it is: https://stackoverflow.com/a/27373951/2748984

Community
  • 1
  • 1
Robert
  • 1,890
  • 2
  • 23
  • 32

1 Answers1

-1

You could do something like the following, which listens for elements being added to the document, and then binds your function. I would also recommend binding an event listener rather than assigning your method to the onclick attribute, but check out this answer to see what you really need:

    // listen for new elements being added to the document
    document.addEventListener('DOMNodeInserted', function(event) {
        // check if they're the type of node you're looking for
        if (event.relatedNode.querySelectorAll('your selector')) {
            // bind the event listener
            event.relatedNode.addEventListener('click', function(event) {
                // your code
            });
        }
    });
Community
  • 1
  • 1
treyhakanson
  • 3,904
  • 1
  • 11
  • 31