I need some help adding a class to a div if is has an image to it.
<div class="large-6 columns check-Div">
<div class="custom-table">
<div class="text">
<?php echo $latestimage; ?>
</div>
<div class="custom-table-box">
<?php echo $table; ?>
</div>
</div><!-- end custom-table -->
</div>
if ($j(".large-6.columns.check-Div > .custom-table-box:contains('size-full')")) {
$j('.large-6.columns.check-Div').addClass("hasImage");
}
The jQuery above is adding the hasImage class to all of the divs but I only want it to apply when there is a div that contains a image. Is there a way to do it singularly? Or by parent? I have tried but I'm a little lost.
Any help would be wonderful!
CSS :has selector is what you are looking for (here for a direct descendant)
$('div:has(> img)').addClass("hasImage") //jquery way
or just in css (but this would require a polyfill, as its in Level 4, which is draft currently)
div:has(> img) {
border-color: 1px solid red;
}
https://developer.mozilla.org/en-US/docs/Web/CSS/:has
JSfiddle here: https://jsfiddle.net/y6gtt2vg/1/
Browser support
About CSS Selector Compatibility
Regardless of a browser's support of CSS selectors, all selectors listed at api.jquery.com/category/selectors/ will return the correct set of elements when passed as an argument of the jQuery function.
You can do this by removing the if statement and just adding the class based on the :has selector:
$j('.large-6.columns.check-Div:has(img)').addClass('hasImage');
You can do this using jquery no need to add if condition
jQuery(".custom-table-box:has(img)").parents(".check-Div").addClass("hasImage");