Applying a class to a single div element

I am struggling with adding a class to a specific div only if it contains an image.

<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 code above is currently adding the hasImage class to all divs, but I want this class to be added only when the div actually contains an image. Is there a way to achieve this for individual instances or by parent element? Any guidance would be greatly appreciated!

Answer №1

By utilizing jQuery, you can achieve this without the necessity of including an if condition.

jQuery(".custom-table-box:has(img)").parents(".check-Div").addClass("hasImage");

Answer №2

To accomplish this task, simply eliminate the if statement and apply the class using the :has selector:

$j('.large-6.columns.check-Div:has(img)').addClass('hasImage');

Answer №3

To enhance readability, I have included a different background color

$(".custom-table").children("div").each(function(item,index) {
  $(this).has("img").css("background-color", "blue"); // Uncomment this line if necessary
  $(this).has("img").addClass("hasImage");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="large-6 columns check-Div">
    <div class="custom-table">
      <div class="text">
        xyz<img />
      </div>
      <div class="custom-table-box">
      abc
      </div>
    </div>
  </div>

Answer №4

If you're searching for the CSS :has selector (specifically for a direct descendant), look no further:

$('div:has(> img)').addClass("hasImage") //this is the jQuery method

You can also achieve this using just CSS, but keep in mind that it currently requires a polyfill since it's part of Level 4 which is still in draft phase:

div:has(> img) {
   border-color: 1px solid red;
}

Learn more about the :has selector at https://developer.mozilla.org/en-US/docs/Web/CSS/:has

Check out the example on JSfiddle here: https://jsfiddle.net/y6gtt2vg/1/


Browser Support

Understanding CSS Selector Compatibility

Even if a browser doesn't fully support certain CSS selectors, they will still work correctly when used with jQuery. Find more information about browser support at https://jquery.com/browser-support/

Answer №5

Consider utilizing an id for this task.

<div id="addImg" 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('#addImg').addClass(".hasImage");//also missing . for class
              }

Answer №6

Here is a suggestion for you

$('.large-6 .columns .check-Div div:has(img)').addClass('hasImage');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Service Worker unable to register due to an unsupported MIME type ('text/html') declared

Working on a project using create-react-app along with an express server. The pre-configured ServiceWorker in create-react-app is set up to cache local assets (https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README ...

Image superimposed with vertical dimension

I have a photo with specific dimensions and I want to create a div box with a button inside the image, similar to what is shown in this example: Example Image Here is my current code attempt: .wrapper { width: auto; text-align: center; } .wrapper: ...

Performing a multitude of if statements simultaneously consistently results in an undefined outcome after the sixth iteration

Oops! I can't believe I forgot my original question! Every time I run the sixth if statement in my code, I encounter a typeError Undefined. Interestingly, when I switch the positions of the fifth and sixth statements, the if(!data.body.main) condition ...

Incorporate external JavaScript libraries not built with Angular

Our project utilizes NPM in conjunction with Browserify for managing third-party dependencies, which pairs well with AngularJS due to the CommonJS-modules. Below is a code snippet showcasing the dependency structure that integrates seamlessly with Angular ...

Exploring the Power of Modules in NestJS

Having trouble with this error - anyone know why? [Nest] 556 - 2020-06-10 18:52:55 [ExceptionHandler] Nest can't resolve dependencies of the JwtService (?). Check that JWT_MODULE_OPTIONS at index [0] is available in the JwtModule context. Possib ...

What is the best way to vertically align an h1 heading in the content area of

I attempted to center my h1 within the body tag using the following code: h1 {margin:0 auto} http://jsfiddle.net/qPDwY/ However, it did not appear to center. What steps can I take to correct this issue? ...

Guide to turning off the pinch-zoom feature on Windows 8 laptops

I'm currently working on a Windows 8 desktop application where I am using C#, JavaScript, and HTML5. Specifically in the C# portion, I am utilizing the WebView object. My goal is to disable pinch-zoom within my application. I already know how to achi ...

inconsistency in button heights

I am currently working on a website project for one of my college courses and I have encountered an issue with the button heights in my slide show not matching up. I'm seeking advice or tips on how to align both buttons to have the same height. Can an ...

A step-by-step guide on implementing ng-annotate to your code

Is there a way to run ng-annotate through the command line? I am attempting to combine and minify Angular, Angular Routes, and my own script.js into one file. When I use grunt uglify:app1, I encounter an injection error. While my code successfully minifies ...

What is the best way to retrieve a file's creation date using the file System module in Node.js

I'm having trouble fetching the filename and file creation date to send to a client. I tried using fs.stat which provides birthtime but does not include the filename. So, my question is: is birthtime equivalent to the file created date? How can I sen ...

JavaScript - Issue with For Loop when Finding Symmetric Difference

Here is my solution to a coding challenge on FreeCodeCamp called "Symmetric Difference." I'm puzzled as to why my code is returning 2, 3, 4, 6 instead of the expected 2, 3, 4, 6, 7. function sym(args) { args = Array.from(arguments); var new ...

Creating a fading header effect with a gradual transition as it disappears

I'm working on a header that should disappear when the user scrolls down and reappear when scrolling back up. I've managed to make the header reappear with a smooth transition, but the disappearing effect is instant, which is not what I want. I n ...

Create a circular div that fills in when hovered over using CSS

I attempted to create an interesting effect when hovering over a circular div, but I struggled to figure out how to fill it in with the same round shape. Currently, the fill is in a square shape, but I am looking to have it match the shape of the div (whi ...

React powered interactive tables

I am in the process of creating a dynamic table using React, and here is the data structure I am working with: { numRows: 2, numCols: 3, cells: [ { id: 1, pos: { row: 1, col: 1 }, content: 'This is th ...

Best practice for structuring an object with multiple lengthy string elements in the GCP Datastore Node Library

My JavaScript object is structured like this: const data = { title: "short string", descriptions: [ "Really long string...", "Really long string..." ] } I need to exclude the long strings from the indexes, but I ...

Getting Your Content Centered Horizontally with Fixed Positioning in CSS

I would like the div to be centered horizontally with a fixed position, but it doesn't seem to work in my code. Can someone help me troubleshoot? Check out the demo here. HTML: <div id="fancybox-thumbs" class="bottom" style="width: 675px;"> ...

Internet Explorer 11's readyState is consistently 'loading' and the DOMContentLoaded event is not firing because of non-SSL content

When using IE11 and encountering the user prompt Only secure content is displayed. #Show all content# The readyState remains constant at loading and the events do not trigger. Everything works fine once the user clicks on Show all content. Unfortu ...

Utilizing Selenium for web scraping on Google Maps consumes an excessive amount of data

Scraping travel times from Google Maps is a task I have successfully accomplished. The code below scrapes travel times between 1 million random points in Tehran utilizing multiprocessing for efficiency. You can run the code provided in a terminal environme ...

What could be the reason for the token being undefined on the client side?

I have built an ecommerce site using nextjs and mongoose, integrating a jwt token in a cookie for client-side authentication. However, when trying to retrieve the token from the cookie named OursiteJWT, I encountered issues with it being undefined: https: ...

Issue with Node.js: Promise not completing execution

My current project involves retrieving data from multiple collections in MongoDB using Node.js and promises. Below is a snippet of the basic code I am using: await Promise.all( ["a", "b", "c"].map(async (collection) =& ...