1

I have made this:

<span class="a">test 1</span><div></div>

Why .b does not activate the alert?

$( ".a" ).click(function() { 
$('div').html('<span class="b">test 2</span>');
});

$( ".b" ).click(function() {
alert("Hello");
});

I do not understand how to detect the mutation of the DOM.

Segala Mirco
  • 69
  • 1
  • 5
  • Possible duplicate of [Click event doesn't work on dynamically generated elements](http://stackoverflow.com/questions/6658752/click-event-doesnt-work-on-dynamically-generated-elements) – Yuval Pruss Mar 18 '17 at 17:12

3 Answers3

0

The selector runs on execution, meaning that .b was already searched for when the page loaded, rather than after you added the dom.

To demonstrate how selectors run in line, the code works if you define it right after appending the element:

$( ".a" ).click(function() { 
  $('div').html('<span class="b">test 2</span>');
  $( ".b" ).click(function() {
  alert("Hello");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="a">test 1</span><div></div>

However, the correct way of doing this would be to define a parent-based selector. The following is setting a click event to the parent that filters the target for the .b selector.

$( ".a" ).click(function() { 
  $('div').html('<span class="b">test 2</span>');
});

$(document.body).on("click", ".b", function () {
  alert("Hello");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="a">test 1</span><div></div>
Neil
  • 14,063
  • 3
  • 30
  • 51
0

since .b is created after the query was done. when you call $(".b") in your script nothing is found, and the click event is not attached to it. You can solve it by attaching the event to the document like so:

$(document).on("click", ".b", function () {
  alert("hello");
});
Shiran Dror
  • 1,472
  • 1
  • 23
  • 36
0

The click() binding you're using is called a "direct" binding which will only attach the handler to elements that already exist. It won't get bound to elements created in the future. To do that, you'll have to create a "delegated" binding by using on().

$('div').on("click", ".b", function () {
  alert("hello");
});
Yuval Pruss
  • 8,716
  • 15
  • 42
  • 67