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?
You’re getting the ID but selecting it as a
.classselector (so it should be$("#"+test)), but it can be easier, like this: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:
Using a
.empty()call will cleanup theclickhandler 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.