Reputation: 885
So, first of all, I am a newbie in Web (html/js)
What I want to achieve:
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>'
);
});
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
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