Search code examples
jqueryelementexistsvisible

If element is visible do something to another element. Jquery


I have multiple containers like this

<div class="container">
    <span>
     <!-- Inside the span is either text or img -->
    </span>
</div>

Goal is to have border around ".container span" only if it contains and image.

i tried something like this.. but it doesnt work

if( $(this).find('.container span img').is(":visible") ){ $(".container span").css({'border':'10px'}); }

Solution

  • visible is a pseudo selector so it's

    .is(':visible')
    

    You can also use it like so

    $(this).find('.container span img:visible')
    

    EDIT

    Hey, wait, are you saying that it might not contain an image at all? In that case, you don't want to be checking for visibility, but rather something like

    $(this).find('.container span img').length > 0
    

    (of course, if there might be images, and they might be hidden, you want to check the length of img:visible)


    EDIT 2

    Now you've got a working check as to whether or not there is a visible image. The rest depends on your implementation. I assumed from the use of $(this) that there will be a DOM node of some kind to search within, that'll only have one .container for each value of this.

    If that's not the case - if you want to look at all of the DOM in one go - you could go about something like this:

    $('.container span img:visible').each(function() {
        $(this).closest('span').css('border', '10px');
    });
    

    Above, you're saying that "for all visible images inside a span inside a .container, add a border to their parent spans.

    Another way of doing it would be something like this:

    $('.container span').filter(function() { return $(this).find('img:visible').length > 0; }).css('border', '10px');