3

Below is my code, why isn't it working when I click on Appended text ?

1: click on This is a paragraph.

2: click on Appended text

3: Must show Appended item with color red.

$(document).ready(function(){
    $(".ali").click(function(){
        $(this).parent().append("<b class='reza'>Appended text</b>");
    });
    $(".reza").click(function(){
        $(this).append("<li style='color:red'>Appended item</li>");
    });
});
<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>

    <p><span class="ali"> This is a paragraph. </span> </p>


</body>
</html>
rrd
  • 5,789
  • 3
  • 28
  • 36
Alireza
  • 87
  • 7
  • 1
    Possible duplicate of [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Sebastian Simon Aug 31 '17 at 05:27

2 Answers2

6

Since the element with class "reza" is not created yet, you need to define click event on future element with "reze" class. Check the below working code.

$(document).ready(function(){
    $(".ali").click(function(){
        $(this).parent().append("<b class='reza'>Appended text</b>");
    });
    $("body").on("click",".reza",function(){
        $(this).append("<li style='color:red'>Appended item</li>");
    });
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>

<p><span class="ali"> This is a paragraph. </span> </p>


</body>
</html>
Radhesh Vayeda
  • 881
  • 7
  • 20
1

Elements which are dynamically added to the document, can not be issued event listeners by normal means.

This is how you would normally add an event listener in jQuery.

$(element).on('click', function() {
    // do something
});

The reason the example above won't work with a dynamically added element is due to the fact that the element doesn't exist when the script gets compiled.

So why does this work?

$(parent).on('click', 'element' function() {
    // do something
});

This works because when the file gets compiled, the parent already exists. If you have a reference to the parent, then you can retrieve the children at anytime. Since the DOM is modular.

This question, in one way or another, has already been asked multiple times. Here's the preferred answer.

Event binding on dynamically created elements?

Lars Peterson
  • 1,508
  • 1
  • 10
  • 27