0

I have the html

<div id=1>
  <span id=2></span>
</div>
<div id=3>
</div>

I'm trying to replace span with a and use the anchor to .toggle() <div id=3>

$('#2').replaceWith(function(){
  return $("<a id=\"2\" href=\"#\" />").append($(this).contents());
});

This works at turning the span to an anchor, but when I try to chain a click function .toggle(), it refuses to toggle.

$('#2').replaceWith(function() {
  return $("<a id=\"2\" href=\"#\" />").append($(this).contents());
}).click(function() {
  $('#3').toggle();
  return false;
});

The click function .toggle() works if I remove .replaceWith().

gavsiu
  • 757
  • 5
  • 9
  • 27

2 Answers2

0

My final solution

$('#2').replaceWith(function(){
  return $('<a id="' + $(this).attr('id') + '" href="#" />').append($(this).contents());
});

$('#2').click(function() {
  $('#3').toggle();
  scrollToDiv($(this),0);
  return false;
});
gavsiu
  • 757
  • 5
  • 9
  • 27
0

You are binding to the element you just removed.

$('#2') // <-- here you already selected the span
// now you replaced it with a new element
.replaceWith(function() {
  return $("<a id=\"2\" href=\"#\" />").append($(this).contents());
})
// the selector is still on the span so you bound the click event to the span
.click(function() {
  $('#3').toggle();
  return false;
});

What you can do is use delegation so it doesn't matter what changes you make to the element. Bind it to a parent element

$('#1').on('click','#2',function(){
      //your code here
});

Now your parent element will listen to the click events that bubble up and handle them.. So it doesn't matter how many times you change the #2 element - as long as it's id=2 then it will trigger the handler

wirey00
  • 33,517
  • 7
  • 54
  • 65
  • In my actual code, #1 is actually does not have an ID, just a common class. Will `$('#2').parent();` work? – gavsiu Jan 31 '13 at 20:04
  • You can use any parent element.. one that you can select.. or if not you can always opt to use 'body' – wirey00 Jan 31 '13 at 20:06
  • I think you're right, but I found that if I don't chain the click function with the replaceWith, it works. Just select #2 again. – gavsiu Jan 31 '13 at 20:17
  • @gavsiu yeah that will work too.. It's because you select the the element and bound it to the correct one where chaining will bind to the element that was removed. Delegation makes it so dynamic changes to the dom will not affect it because the event handler is attached to the parent.. so it doesn't how many times you change #2 - when the event bubbles up the parent element will handle the event – wirey00 Jan 31 '13 at 20:23