Reputation: 1766
Imagine I have three different types of product HTML and I want to select the product-block
element for only those that have a child or sibling with an input element that has a class mySelector
.
The goal is to select the product block <div>
of types A and C, which have a child or sibling with mySelector
.
Product block type A
<div class="A B C">
<a href="#"></a>
<input type="hidden" class="mySelector">
</div>
Product block type B
<div class="MM NN OO">
<a href="#"></a>
</div>
Product block type C
<div class="X Y Z">
<a href="#"></a>
</div>
<input type="hidden" class="mySelector">
I imagine a filter could work, but I only can select one type of product-block with a filter like this:
jQuery('.mySelector')
.filter(function () {
if (jQuery(this).prev().hasClass('Z')) {
return jQuery(this).prev();
}
})
Another approach is using jQuery('.mySelector').parent()
. But then I would not be able to select type C where mySelector
is a sibling.
Upvotes: 1
Views: 23
Reputation: 1766
I solved it as @freedomn-m suggested.
let elmsa = jQuery('.mySelector').parent()
.filter(function () {
if (jQuery(this).hasClass('A')) {
return this;
}
});
let elmsb = jQuery('.mySelector').prev()
.filter(function () {
if (jQuery(this).hasClass('X')) {
return this;
}
});
let elms = jQuery.merge(elmsa, elmsb);
Upvotes: 1