0

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?

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.