Snowcat Jung Snowcat Jung - 5 months ago 27
CSS Question

How can I select other div's child in jQuery?

I want to select all previous ".pt" when I checked some element.

I tried

$('p').mouseover(function(){
$(this).css('font-size', 'bold');
$(this).prevAll('.pt').css('font-size', 'bold');
});


In second div, it just changed previous ".pt" in second div.

How can I changed first div's ".pt" even when checked second div element?

<div> //first
<p class="pt p1"></p>
<p class="pt p2"></p>
<p class="pt p3"></p>
</div>

<div> //second
<p class="pt p1"></p>
<p class="pt p2"></p>
<p class="pt p3"></p>
</div>

Answer

You can try getting the index of the element and then slice with that parameter:

$('.pt').click(function() {
  $('.red').removeClass('red');
  var ti = $(this).index('.pt');
  $('.pt').slice(0, ti + 1).addClass('red');
})
.pt {
  padding: 15px;
  background: gold;
  margin: 8px;
}
.red {
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <p class="pt p1"></p>
  <p class="pt p2"></p>
  <p class="pt p3"></p>
</div>

<div>
  <p class="pt p1"></p>
  <p class="pt p2"></p>
  <p class="pt p3"></p>
</div>