Reputation: 7490
I know if I have to access all the children with class child
of parent with class parent
we write
$('.parent .child')
But I don't know how to access parents with class parent
of child with class child
.
My situation is, I want to color all divs with class lmn
red who are immediate previous element with class abc
and .abc
has an element with class pqr
. My mark up becomes
<div class='lmn'>
Prev of 1
</div>
<div class='abc'>
1 - 1
<div class='xyz'></div>
</div>
<div class='abc'>
1 - 2
<div class='pqr'></div>
</div>
<div class='lmn'>
Prev of 2
</div>
<div class='abc'>
2 - 1
<div class='xyz'></div>
</div>
<div class='abc'>
2 - 2
<div class='pqr'></div>
</div>
and jquery
$(".pqr").closests('.abc').prevAll(".lmn:first").css("color", "red");
but it is making only first div vlmn
red, even though both divs .lmn
satisfies my situation.
Do I have any replacement for $(".pqr").closests('.abc')
that give me both .lmn
or I have to use $.each
which I was thinking of avoiding?
Upvotes: 0
Views: 87
Reputation: 21
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
function colorLmn(){
$(".pqr").closest('.abc').prevAll(".lmn").css("color", "red");
}
</script>
</head>
<body>
<button onclick="colorLmn()">Color Lmn</button>
<div class='lmn'>
Prev of 1
</div>
<div class='abc'>
1 - 1
<div class='xyz'></div>
</div>
<div class='abc'>
1 - 2
<div class='pqr'></div>
</div>
<div class='lmn'>
Prev of 2
</div>
<div class='abc'>
2 - 1
<div class='xyz'></div>
</div>
<div class='abc'>
2 - 2
<div class='pqr'></div>
</div>
</body>
</html>
Upvotes: 0
Reputation: 318192
You'd target all .abc
that has .pqr
and then find the previous element, and filter based on the class lmn
$('.abc:has(.pqr)').prev('.lmn').css('color','red')
You don't have any lmn
that are immediate previous element of abc
that also contains pqr
, so no elements match your condition.
Upvotes: 1