Check Children of Parent and if Child "Has Class" - Do something...Not working (jQuery)

Hi there. I’m trying to select a div parent, but ONLY if that div has a child element with the class .refills.
For some reason, though I’ve wrapped this in an each, and if statement, the result is “TRUE” even though it’s not true for the second item. What am I missing here?

PEN: https://codepen.io/brittany-golden/pen/bGGXeBe

Thanks!

Couldn’t you just say.

$(".line-item-title .refills").closest(".line-item-info").addClass("HELLO");

Or even:

$(".refills").closest(".line-item-info").addClass("HELLO");

In your original you would need to add .length to the if statement.

e.g.

// Check Each Product and if statement is true, add class to closest parent
$(".line-item-title").each(function() {
  if ($(this).has(".refills").length) {
    // find the parent and add class ONLY if the "IF" is true
    $(this)
      .closest(".line-item-info")
      .addClass("HELLO");
  }
});

I think your original fails because has returns a jQuery object which is always true so you need to check the length property.

1 Like

Hi there birdiegolden,

perhaps this Vanilla example will help…

https://codepen.io/coothead/pen/RwwXGmx

script

<script>
(function( d ) {
   'use strict';
   var c, elem = d.getElementsByClassName( 'refills' );
   for ( c = 0; c < elem.length; c ++ ) {
      if ( elem[c].parentNode.className === 'line-item-title' ) {
           elem[c].classList.add( 'extras' );
        }
      }
}( document ));
</script>

coothead

1 Like