0

I need some help in jQuery. When the page is loaded, I have a tag:

So I can select it in my script by: $('#root-directory')

Then, I select it and add some contents within when it is clicked by using the .html() jQuery function.

These contents contains new elements with a class name (example: "has-child") that is never used before in the page.

After that, I create a function which must manipulate the class has-child.

And the issue appear on this function, it finds any elements with this class even if the elements can be inspected in the DOM. In the same way, if I create a trigger using this class name, it will return an error.

So, the solution I'm searching for is how manipulate the "has-child" elements in my script.

<ul id="root-directory"></ul>
let root = $('#root-directory');

$(root).on('click', function(){
    let html="";
    for(let i = 0; i < 4; i++) {
        if(i % 2 === 0) {
            html += `<li>item number ${i}</li>`
        }
        else html += `<li clas="has-child">item number ${i} with child</li>`
    }
})

$('li.has-cild').click(function(){
    //...Add some new contents
})
//And this return a reference error because the selection is said undefined.
Tyler Roper
  • 21,445
  • 6
  • 33
  • 56
Nickce
  • 9
  • 1
  • 1
    You have a typo: `has-cild` More importantly though, you should read up on **event delegation**. Possible duplicate of [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Tyler Roper Jun 02 '19 at 20:26
  • 1
    And another typo: `li-clas`. You also have to add the html to the page before you can attach the handler. – Kokodoko Jun 02 '19 at 20:30
  • 1
    @Kokodoko *"You also have to add the html to the page before you can attach the handler. "* - while you can't attach handlers to elements that don't exist, you can attach them to the parent and catch the events using propagation. This is the basis for the event delegation that I've described/linked above. – Tyler Roper Jun 02 '19 at 20:31
  • But then why don’t you attach the handler to a parent of the `
  • `, for example an `
      `? (Which I don’t see in your code)
  • – Kokodoko Jun 03 '19 at 06:59
  • @Kokodoko I cannot add the html to the page on load because the html is not static, it depends on which parent is clicked – Nickce Jun 03 '19 at 07:16
  • @Tyler Roper - You mean that I must refer to the parent element loaded on the on load event ? – Nickce Jun 03 '19 at 07:28
  • @Nickce The link in my first comment should explain. You attach your event to any ancestor, e.g. `$(document).on("click", "li.has-child", function() { ... });` - This will fire on click of any `li.has-child`, regardless of how/when it was created. – Tyler Roper Jun 03 '19 at 14:54