1

Using jquery I added an HTML button using insertAfter() now I would Like to select that button by id but didn't work.

$("button").click(function(){
  $("<button id='new-button'>Added Button</button>").insertAfter("#this");
});
$("#new-button").click(function(){
  $("<span> #new-button-work</span>").insertAfter("#this");
})
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>

<button id="this">Insert span element after this element</button>

</body>
</html>
shraysalvi
  • 303
  • 1
  • 10

2 Answers2

3

Because of new-button is inserted after script run so you can try this

$("button").click(function(){
  $("<button id='new-button'>Added Button</button>").insertAfter("#this");
});
$("body").on("click", "#new-button", function(){ <--
  $("<span> #new-button-work</span>").insertAfter("#this");
})
Paul J.K
  • 603
  • 1
  • 4
  • 13
2

Because you're dynamically adding new elements to the DOM you should use event delegation - attaching listeners to a parent element (like document), and then using the 2nd argument of the on method to identify the element you want to match.

$(document).on('click', '#this', function() {
  const button = '<button id="new-button">Added Button</button>';
  $(button).insertAfter('#this');
});

$(document).on('click', '#new-button', function() {
  const span = '<span> #new-button-work</span>';
  $(span).insertAfter('#this');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="this">Insert span element after this element</button>
Andy
  • 61,948
  • 13
  • 68
  • 95
  • Surely you didn't expect this question to have never been asked before. https://stackoverflow.com/questions/34896106/attach-event-to-dynamic-elements-in-javascript – connexo Aug 31 '22 at 18:14