Skip to content Skip to sidebar Skip to footer

Jquery Filter Image Src Issues

if the image contains NO src then i want to hide the div.PageHeaderDescription

Bistro 300

Solution 1:

$("div.PageHeaderDescription img[src='']").parent().hide();

Find img with empty src and hide its parent div.PageHeaderDescription;

DEMO

OR

$("div.PageHeaderDescription").has("img[src='']").hide();

Hide this div.PageHeaderDescription which has img with empty src.

DEMO

Solution 2:

filter() returns a jQuery object, which is always truthy, whether or not elements were matched.

What you should be doing instead is checking the lengthproperty of the object returned;

if ($("div.PageHeaderDescription img").filter("[src='']").length) {
    $("div.PageHeaderDescription").hide();
}

Although you could shorten this to;

if ($("div.PageHeaderDescription img[src='']").length) {
    $("div.PageHeaderDescription").hide();
}

But if you have multiple div.PageHeaderDescription on the page, you should be doing;

$("div.PageHeaderDescription").each(function () {
    var self = $(this);

    if (self.find('img[src=""]').length) {
        self.hide();
    }
});

Solution 3:

If you want to do that when page loads, you can use this code:

$("div.PageHeaderDescription img")     // search for all img's inside a div...
   .filter("[src='']")                 // get only ones with no src
   .parents("div.PageHeaderDescription")   // get their parent elements
   .hide(); // hide then

Or you can run the same script every time you want to check if any img with no src is in page and must be hidden.

Solution 4:

No need to make it more complicated than it needs to be with a .filter().

var phd = $("div.PageHeaderDescription");    
if ($('img:not([src])',phd).length || $('img[src=""]',phd).length) {
    phd.hide();
}

I check to see if the img doesn't have the src attribute or if it does have the attribute I check if it is blank.

Fiddle: http://jsfiddle.net/iambriansreed/G6bPu/

Solution 5:

As already said, a jQuery object always evaluates to true. But you don't need an if statement at all, simply reduce the set of elements to those that have an "empty" image. That's what .filter() is there for:

$("div.PageHeaderDescription").filter(function() {
    return $(this).find("img[src='']").length > 0;
}).hide();

Post a Comment for "Jquery Filter Image Src Issues"