Gol.D Gol.D - 3 months ago 11
jQuery Question

can we add more class selector to $(this)?

Here is the example:-

HTML

<div id="div1">
<span id="span1"></span>
</div>


JS

$('#div1').click(function () {
$(this + "#span1").css("background-color","red");
});


I have tried this but it's not working.
Any help and suggestions are welcomed.
Thank you.

Answer

In your code this + "#span1" outputs like [object HTMLDivElement]#span1 which will not select any element so nothing would happen with your code.


To get element within the clicked context pass this context as the second argument in jQuery.

$('#div1').click(function () {
  $("#span1", this).css("background-color","red");
});


FYI : Since both are id selector and id are unique $("#span1") is enough for your code.


UPDATE : So if there are multiple elements you should use the class instead otherwise only first element with the id get selected.

$('.div1').click(function() {
  $(".span1", this).css("background-color", "red");
});

$('.div1').click(function() {
  $(".span1", this).css("background-color", "red");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div1">
  <span class="span1">1</span>
</div>
<div class="div1">
  <span class="span1">2</span>
</div>
<div class="div1">
  <span class="span1">3</span>
</div>