Jquery - Works with Chaining but not apart

65 Views Asked by At

I'm an experienced developer who is new to Jquery. I'm running into a problem where I have code that works when it chained together but not when it is separate and I would like to understand Jquery behavior.

I have a <div> with 4 buttons in it. When one of the 4 buttons is pressed, I need all 4 buttons to go away and a new button to replace it (the new button is a button with the same value as the one pressed but with different CSS to make it look different)

When the button is pressed I clear the <div> out like this

$(this).parent().empty();

I then build up the new button I want to insert

var splitstr = event.target.id.split('-');
var pick = splitstr[0];
var position_id = splitstr[1];
var singlebutton = '<button class="pick' + pick + ' pickbutton-box btn btn-primary btn-large madepick" name="pick" ' + 'id="made'+ position_id + '" ' + 'value="' + pick + '">' + pick + '</button>';

and then I tried to insert it back into the parent:

$(this).parent().append(singlebutton);

When I do this all 4 of the buttons in the <div> are removed but the new button is not added. However, if I build the string up before I do the empty and append

var singlebutton = " ---- HTML CODE for button ---- "
$(this).parent().empty().append(singlebutton);

Everything works as expected. This doesn't seem to make any sense to me. Can someone please explain what is happening.

1

There are 1 best solutions below

1
bfavaretto On

You state you have something like this:

<div>
    <button>click me</button>
    <button>click me</button>
    <button>click me</button>
    <button>click me</button>
</div>

And an event handler like this:

$('div button').click(function() {
   $(this).parent().empty();
   // etc
});

When your handler code runs, this points to the clicked button, which is removed by $(this).parent().empty();. You'd need to save a reference to the parent div to be able to reference it later, because this will become empty. Something like this:

$('div button').click(function() {
   var div = $(this).parent().empty();
   // cannot use 'this' anymore below this point
   div.append('something');
});

The chained version works because a reference to the parent element is what is passed ahead starting from .parent, and the value of this becomes irrelevant.