Using JQuery selectors to locate elements with or without child elements

Below is a demonstration of HTML code:

<div class="container">
   <div class="zone">
       <img class="thumb" alt="GG">
   </div>
   <div class="zone">
       <span>&nbsp;</span>
   </div>
   <div class="zone">
       <img class="thumb" alt="HH">
   </div>
</div>

I am trying to select all div elements with the class zone that either have an img element with the attribute alt=GG, or no img at all.

The current code snippet is not working as expected:

$('div.zone img[alt="GG"], :not(div.zone:has(img))')

Answer №1

Give this a shot:

var $specialDivs= $('div.zone:has("img[alt="GG"]"), div.zone:not(:has(img))');
                              ^    ^                          ^        ^
                              |    |                          |        |
                       div.zone contains image with alt      div.zone without any images            

Check it out here

The problem with your selector is that 'div.zone img[alt="GG"] - the space between div and image will search for a div.zone that has children with the image having the alt attribute. Since the image is a direct child of div.zone, your selector won't return anything.

Answer №2

To apply a filter, you can utilize the filter function in your jQuery code snippet below:

$('div.zone').filter(function() {
   return !$(this).find('img').length || $(this).find('img[alt="GG"]').length
});

View Fiddle Example

Answer №3

Forget Jquery, CSS selectors can get the job done: Check out the DEMO

Take a look at this CSS selector:

.container > div.zone img,
.container > div.zone img[alt="GG"] {
    background: red;
}

Best regards, Leo!

Answer №4

Give this a try. It definitely works, highlighting the desired areas in RED outline. (Edited: Appreciate PSL's contribution)

$(document).ready(function(){
$("div.zone:has(img[alt='GG']),div.zone:not(:has(img))").css("border","1px solid red");
});

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

Angular application's NgbTooltip positioning

Within my Angular 2/4 project, I am utilizing ng-bootstrap along with its NgbTooltip component. Consider this HTML snippet: <div class="col-sm-8 text-ellipsis" ngbTooltip="'A very long text that does not fit'" placement="top" ...

Using different CSS classes interchangeably in AngularJS

Imagine you have a list with an unknown number of items, ranging from one to potentially dozens. You want to display five CSS classes in a regular alternating pattern. What would be the most effective approach to achieve this? Here is some sample HTML cod ...

Implementing jQuery function to hide or show content upon page load

Is there a way to have the content hidden when the page is first opened, but then revealed once a button is clicked? Any suggestions? <script> $(document).ready(function(){ $("#rooms").click(function(){ $("#rooms_box").show(); }); $("#faciliti ...

What is the syntax for creating a jQuery object using the noConflict() function?

Can an object called response be defined without using the dollar sign ($)? This is how my code will appear: jQuery.get("test.pl", { action: "getNextID" }, function(data) { var response = jQuery(data); }); ...

Create two unique jQuery click events for the same element

I am working on a website where I have implemented a button that uses jQuery to change the CSS of certain elements when clicked. Now, I am looking for a way to assign another function to revert the CSS changes back to their original state when the button ...

How can I stack two images on top of each other using z-index?

Within a div element, I have an image: <div class="full-width"> <img src="images/products/product1.jpg" /> </div> I am looking to introduce another image called frame.png, but not as a background image! <img src="images/products ...

Tips for concealing the edges of a scroll bar while utilizing scroll as overflow

Basically, I have a div that is positioned absolutely and has multiple children elements. This div can be scrolled horizontally to see all its content, but the scrollbar hangs off the bottom, hiding the bottom border radius. Here is the HTML code: <ul ...

Issue with Zeroclipboard not copying content when initially clicked

My code is experiencing some issues where it doesn't work on the first click, but strangely works on the second click. $("#btnCopiar").on("click",function(){ var clipBoardObj = new ZeroClipboard($("#btnCopiar"), { moviePath: ".. ...

Button failing to align properly in the center position

I was able to successfully create a responsive input box, but for some reason, the button is not aligned in the center. Below is the CSS code: .webdesigntuts-workshop button { background: linear-gradient(#333, #222); border: 1px solid #444; border- ...

Does Sublime Text 2 offer intelligent intellisense with jQuery suggestions that are not just snippets?

Is there a way to achieve the same level of detailed assistance in my lightweight Sublime Text 2 as I do with vs2012? Most packages I've tried focus on snippets rather than providing smart hints. In vs2012, I used -vsdoc to solve this issue. How can I ...

When rendering a partial from a js.erb template, the resulting content may contain remnant html tags

I am having trouble displaying the results from show.js.erb. Here is the current output: show.js.erb $('#results').empty(); $('#results').html("<ul><%= escape_javascript(render(@results)).html_safe %></ul>"); _resul ...

Encountered a critical issue while converting SVG to PNG with readimageblob

I am attempting to utilize Image-Magick in combination with PHP to transform SVG text into a PNG image. The SVG in question is a chart produced with NVD3 and my goal is to enable users to download it as an image. The process involves sending the SVG data, ...

Retrieving information from database with the help of PHP and AJAX

I am having trouble printing data from a PHP and Ajax request that is initially encoded into JSON. Instead of displaying the data properly on the screen, it is showing elements from four rows all in a single line with commas separating them. $(document ...

Select an image from the browser using JavaScript, adjust its size, and then transmit it to the server. Finally, utilize PHP to properly save the image

I am currently tackling the challenge of implementing a classical feature where users can select a file in their browser ("Browse"), have JavaScript resize it to a maximum width/height of 500 pixels, upload it to the server, and then save it to disk using ...

Delivering styled coldfusion outcomes utilising css and jquery

After using jquery to retrieve some data, I've noticed that the results are displayed correctly but the CSS is not being applied. Is there a way to style the results with CSS? function doSearch() { //Making an AJAX call to the server $.ajax({ / ...

Choosing choices from an array of values in a selection box

Using Ajax request with Jquery, I am receiving some values in JSON format. When I try alert(msg.options), it displays ["1","3","8"] The following script successfully selects the required options with values 1, 3, and 8: $('#input_6').val(["1"," ...

What is the best way to modify the color of the active tab I have chosen?

I've designed a tab menu using Divs and CSS, but I'm facing an issue with changing the color of the selected tab. I tried adjusting the background color of the .tab class, but it seems to only work for part of the tab... You can view the problem ...

Using Bootstrap and CSS to style a div element and fill it

I'm struggling with a div that splits in two, where I've placed an image on the left side. However, the image doesn't seem to fill the entire space and there are empty spaces on the sides. I'm using bootstrap, but any CSS solution would ...

Trim the edge of a dynamic picture

Currently, I am facing a challenge with an image that requires the corner to be cut off. The image needs to be responsive in order to adjust its size according to the page dimensions. Since the image is managed by a CMS, the corner cut has to be done progr ...

Navigational elements, drawers, and flexible designs in Material-UI

I'm working on implementing a rechart in a component, but I've encountered an issue related to a flex tag. This is causing some problems as I don't have enough knowledge about CSS to find a workaround. In my nav style, I have display: flex, ...