I've seen other questions that were supposed to answer mine, however for some reason, they did not. I am referring to these:
- jquery click event not firing?
- jquery functions dont work on dom elements loaded asynchromously
I first used click() to try to change the color of selected "li" to pink. It worked, but not for the "li"s appended dynamically. I tried to use on() since live() is now deprecated. I was surprised that it still did not work.
This is a sample that you can run:
Javascript:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("ol").append("<li class='test'> Appended item </li>");
});
});
</script>
<script>
$(function () {
$('.test').on('click', function () {
$(this).css("background-color","pink");
});
});
</script>
HTML:
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<ol>
<li class='test'> List item 1 </li>
<li class='test'> List item 2 </li>
<li class='test'> List item 3 </li>
</ol>
<button id="btn1">Append list item</button>
</body>
Does anyone have a clue?
Thanks a lot!