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?



Couldn’t you just say.

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

Or even:


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


// 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

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…


(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 ));


1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.