andrgolubev
andrgolubev

Reputation: 885

JQuery: dynamically update HTML so that it is recognized by JQuery

So, first of all, I am a newbie in Web (html/js)

What I want to achieve:

  1. I have a custom tree and I want to be able to dynamically (using jquery) create children for that tree:

Html:

    <ul>
      <li>
        Item
        <input type="button" value="+" class="childAdder">
        <ul class="childrenList"></ul>
      </li>
    </ul>

JS:

$(".childAdder").click(function() { // add child which is the same as root
  $(this).parent().children(".childrenList").append(
    '<li>Item</li>\
     <input type="button" value="+" class="childAdder">\
     <ul class="childrenList"></ul>'
  );
});
  1. And as you can see, I know how to add a child (more or less, an advice is always welcomed). The problem is, however, that this code only works for items that are "predefined" in html --> everytime I dynamically(via JS) add a child, this code just does not execute for this newly created element (tried to do alert('Hello'); - nothing is seen)

Question: I assume I need to somehow "properly" add my new child to the DOM(?) of HTML or whatever, so that it is then recognized by JS, right? (but that seems to be only achieved trough HTML static page, no?)

Anyway, how do I make this thing work: add new child so that the same JS code that is executed for HTML element is executed for the element created by JS

Upvotes: 0

Views: 53

Answers (1)

Scott Marcus
Scott Marcus

Reputation: 65853

You need to use event delegation for this to work. This is done by using the on JQuery method for event wiring and modifying the parameters.

Also (FYI), a <ul> element can only contain <li> elements as children. Your bullet/nested list structure is invalid.

Lastly, in the HTML string you were appending included random \ characters, which are not needed and are actually invalid at those locations.

Here's the correct implementation with the HTML corrected to be valid.

// JQuery event delegation requires the use of the "on" method and then you 
// bind the event to an object that is sure to always recieve the event (document 
// works well here because of event bubbling). Then you specify the target element
// that the actual event will be triggered from.
$(document).on("click", ".childAdder" ,function() { 
  // add child which is the same as root
  $(this).parent().children(".childrenList").append("<li>Item<br><input type='button' value='+' class='childAdder'><ul class='childrenList'></ul></li>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
      <!-- <ul> and <ol> elements can only have <li> elements as thier children (aside from
           comments like this one). To properly nest lists, organize the HTML as follows: -->
      <li>Item<br>
        <input type="button" value="+" class="childAdder">
        <ul class="childrenList"></ul>
      </li>
 </ul>

Upvotes: 3

Related Questions