0

Here is a sample 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 want to match all div with the zone class that have img with alt=GG or no img at all.

The following code doesn't work:

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

4 Answers 4

3

You can try this:

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

Fiddle

issue with your selector is that 'div.zone img[alt="GG"] a space between div and image will look for the div.zone whose children having the image with alt attribute. whereas the image is direct descendant of div.zone, hence your selector will not get you anything.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use the filter method

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

Check Fiddle

1 Comment

I'd prefer a solution with selector only.
0

You don't need Jquery for do this. Just with CSS selectors you can do it: DEMO

Here is the CSS selector:

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

Cheers, Leo!

1 Comment

I'm sorry , your answer is incorrect since it doesn't match the second div.
-1

Try this. It confirm works, the wanted zone are bordered RED. (Edited: Thanks PSL)

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

4 Comments

This doesn't give a div this gives image and a div. instead of 2 divs that meets the criteria.
Now you edited how is it different from my answer? I posted ages back.
Edited. Hopefully TS revisit the answer. Yeah. Apparently, the modified answer is the same. I missed the div.zone on the second part as well.
Exactly that is what i meant. There is already a similar answer posted times back. Also your edit history shows your old answer which was apparently wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.