1

Before I ask the question refer to this jsFiddle: http://jsfiddle.net/AxGHA/3/

I basically want to remove the float: left; StyleSheet attributes on the H2 and P tags IF no image exists within the div with jQuery. Any ideas?

Thanks!

1
  • @simchona: I tried using CSS to make it work, and that doesn't work. Commented Apr 19, 2012 at 16:43

6 Answers 6

7

you can use :not and :has I have done an example code below:

$(".section:not(:has(>img))").addClass("no-image");

and the CSS for that:

.no-image h2, .no-image p {
    float: none;
    width: auto;
}

example: http://jsfiddle.net/voigtan/AxGHA/5/

">img" instead:

http://jsfiddle.net/voigtan/AxGHA/6/

I'm adding a css class to the .section and style it in the css on how I want it to look.

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

2 Comments

@voigtan: This is actually great, but for some reason it is not wanting to work. And plus I forgot to add that within the h2 element there is an image to the right, kind of like an arrow to resemble the element. Thank you so much for your help!
you can just change the :has(img) to :has(>img) to see if the .section has a direct child of an image: jsfiddle.net/voigtan/AxGHA/6
2
if(!$('div.section img').length) {
   $('p, h2', 'div.section').css('float', 'none');
}

Comments

2

You can do this

$(".section").each(function() {
    var hasImage = $(this).children("img").length != 0;
    if (!hasImage) {
        $(this).find("h2,p").css("float", "none");
    }
});

​

Check out the updated jsFiddle

Comments

1
    ​$(document).ready(function(){
    if ($("div.section").find("img").length == 0){
        $("h2.section, p.section").css("float", "none")            
    }
});​

Comments

1
!​$('.section img​​​​​​​​​​​​​​​​​').length && $('.section h2, .section p').css('float', 'none');

Comments

1

I think you can do something like this (notice that I didn't test the code):

$('h2, p').parent('div').each(function(index, $element) {
    if (!$element.has('img'))
        $element.css('float', 'none');
});

Notice that I can't view the jsfiddle from where am I so I based the answer directly on what you explained.

Comments

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.