0

The issue with detecting and using id within replaceWith or new HTML code

Hi, I'm having an issue with replaceWith. When I click on the div below and replace the HTML. I am not able to use the id within the new div. I even tried HTML instead of replaceWith and I am still not able to.

<div id="action"></div>

<script>
$("#action").click(function(){
var foo = $(this).attr('id');
//$("#"+foo).html("<div id="next">do this</div>");
$("#"+foo).replaceWith("<div id="next">do this</div>");
});
$("#next").click(function(){
var bar = $(this).attr('id');
alert(bar);
});
</script>
Dominik Matis
  • 2,086
  • 10
  • 15
user836910
  • 484
  • 2
  • 9
  • 22
  • 1
    You need to bind it with static element i.e :`$(document).on('click', '#next', function() {..` – Swati Feb 01 '21 at 13:43
  • 1
    The fact that your code ihas a syntax error is probably getting in the way of things too... – David Feb 01 '21 at 13:43
  • 2
    @Swati correct because your #next id is not present in page load time so the click event can't bind to the #next element – Ben.S Feb 01 '21 at 13:45
  • @Ben.S No, it's posible, you can check my answer below. – Nguyễn Văn Phong Feb 01 '21 at 13:51
  • 2
    @Phong its not possible your code differ from the question code. you registered the click event to #next element in the #action click function so only in that function the binding of the click event is happening and in that moment the #next element exist – Ben.S Feb 01 '21 at 14:00
  • Pls, kindly read my answer with 2 cases, bro ^^! @Ben.S – Nguyễn Văn Phong Feb 01 '21 at 14:01
  • 2
    in the first case registration happening only after the the #next element exist in dom. in second case you append the click event to document element that always exist – Ben.S Feb 01 '21 at 14:03
  • thanks @swati i understand. – user836910 Feb 01 '21 at 16:11

1 Answers1

1

Your sample code has error syntax, So I divided it into 2 possible cases:

  1. Replace HTML then listen the event click sequentially.

$("#action").click(function(){
  var foo = $(this).attr('id');
  $("#"+foo).replaceWith("<div id='next'>do this</div>");
  
  $("#next").click(function(){
     var bar = $(this).attr('id');
     alert(bar);
   });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="action" >action </div>
  1. In case you listen event on separately, you should use $(document).on("click","#next", function(){

$("#action").click(function(){
  var foo = $(this).attr('id');
  $("#"+foo).replaceWith("<div id='next'>do this</div>");
});

$(document).on("click","#next", function(){
   var bar = $(this).attr('id');
   alert(bar);
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="action" >action </div>
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
  • Yes, this was a great help. I tried it and it work. Can you explain why i had to add "on.("click, id,..." ? – user836910 Feb 01 '21 at 16:09