1

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.

  • Type A has the element with 'mySelector' within.
  • Type B doesn't have an element 'mySelector' within or below it, so we don't want to select it.
  • Type C has the element 'mySelector' right after it.

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.

Aleksandar
  • 1,496
  • 1
  • 18
  • 35

1 Answers1

1

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);
Aleksandar
  • 1,496
  • 1
  • 18
  • 35