0

Why this funcion add class only when you click on li elements that are originaly from html file. If i create new li element with add button, then add class doesnt work on it. How can i solve this?

<input type="text" id="new"><button id="add">Add</button>
<ul id="list">
    <li >one</li>
    <li>two</li>
    <li>three</li>
</ul>

javascript

$(document).ready(function(){
$("li").click(function(){
    $(this).addClass("current");
});

$("#add").click(function(){
    var a=$("#new").val();
$("#list").append("<li>"+a+"</li>");
});
});
Soviut
  • 88,194
  • 49
  • 192
  • 260
john12
  • 35
  • 1
  • 3
  • 1
    http://stackoverflow.com/questions/16342220/button-not-working-after-appending-jquery-1-9-1 or: http://stackoverflow.com/questions/15420558/jquery-click-event-not-working-after-append-method or many similar questions... – sinisake Jan 09 '17 at 01:55
  • Note that the problem isn't with `.addClass()`, it is that your click handlers don't apply to the dynamically added elements. – nnnnnn Jan 09 '17 at 05:38

1 Answers1

0

JQuery doesn't check for DOM changes, it's not "live". When you apply a query, it's based on how the DOM is currently structured. Each time you append something you need to apply any changes to those elements.

$("#list").append("<li>"+a+"</li>").addClass('current');
Soviut
  • 88,194
  • 49
  • 192
  • 260