Reputation: 5131
Once clicked on it, I'd like to append a ul element to a li element.
My html is the following:
<ul>
<li>list 1</li>
<li>list 2</li>
<li>list 3
<ul>
<li>list 31</li>
<li>list 32</li>
<li>list 33</li>
</ul>
</li>
<li>list 4</li>
<li>list 5</li>
</ul>
and my javascript:
$('ul').on('click', 'li', function (){
$(this).append(
'<ul>'+
'<li>list a</li>'+
'<li>list b</li>'+
'<li>list c</li>'+
'</ul>'
)
});
My problem is when I click on a li instead of appending the element to the current li, it appends it to all the li being in the same scope.
jsfiddle: https://jsfiddle.net/malamine_kebe/Lneyn80w/
Upvotes: 0
Views: 616
Reputation: 67207
You have to stop the event which gets bubbled up the DOM tree,
$(document).ready(function(e) {
$('ul').on('click', 'li', function(e) {
e.stopPropagation();
$(this).append(
'<ul>' +
'<li>list a</li>' +
'<li>list b</li>' +
'<li>list c</li>' +
'</ul>'
);
});
});
Upvotes: 1