Sergio
Sergio

Reputation: 1239

Jquery variable problem

The HTML:

<div class="first" id="first_id">
<div class="second">text sample</div>
<div class="third"><button type="submit" class="some_class" id="some_id">send</button></div>
</div>

Jquery:

$("#some_id").click(function() {
var test = $(this).closest('.first').attr('id');
..
return false;
});

I want to replace content of the "first" div using var "test" in jquery code above. Something like:

$("."+test).html('<img src="img/spin.gif">');

But when I put this part of the code in function above it does not work. What I did wrong?

Upvotes: 0

Views: 42

Answers (2)

gruszczy
gruszczy

Reputation: 42188

You put id value into the test, but then you use '.' in selector. Instead you should use '#'.

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630429

You're getting the ID but selecting it as a .class selector (so it should be $("#"+test)), but it can be easier, like this:

$("#some_id").click(function() {
  $(this).closest('.first').html('<img src="img/spin.gif">');
  return false;
});

There's no need to go selecting the element again, you already have it, so just calling .html() on the element you found with .closest() works, simpler and faster :)


For completeness sake though, what you should do is this:

$("#some_id").click(function() {
  $(this).closest('.first').empty().append('<img src="img/spin.gif">');
  return false;
});

Using a .empty() call will cleanup the click handler we're in, otherwise it'l be left around in $.cache...this isn't a big issue, but if you have lots of elements it adds up, it's best to always cleanup if possible.

Upvotes: 5

Related Questions