Arne Banck Arne Banck - 4 months ago 15
jQuery Question

Add css to class with style (url) find

Im looping through all divs on a specific page and look for a url thats defined by a theme in 'style' attribute. If I find the url I would like to add css to a specific class. I am getting no errors, can someone take a look where I took a wrong turn?

Code:

if (top.location.pathname === '/news/') {
$j("div").each(function() {
if ($j(this).css('background-image') === 'http://daddykate-acc.daddykate.be/wp-content/plugins/js_composer/assets/vc/vc_gitem_image.png') {
$j('.vc_gitem-zone').css('display', 'none');
}
});
}


Little PS: The
$j
is required to make the code work (WP theme obligation)

EDIT: Ok, so I just used the 'setTimeout' function to make the function run after DOM was loaded. Everything is working fine now, Thank you for all the input !

Answer

Asking for background-image will return somthing like url("http://..."), so your check fails here. I would do something with regex or indexOf:

if( top.location.pathname === '/news/' ) {
    $j("div").each(function() {
        if( $j(this).css('background-image').indexOf('daddykate-acc.daddykate.be/wp-content/plugins/js_composer/assets/vc/vc_gitem_image.png') >= 0 ) {
            $j('.vc_gitem-zone').css('display', 'none');
        }
    });
}

And just a hint, you know that you can wrap your code and use $ instead of $j? This would help you to reuse code on other pages.

You can do it with a ready state of jQuery:

$j(function($) {
    $("div").each(function() { /* ... */ });
});

Or with a IIFE:

(function($) {
    $("div").each(function() { /* ... */ });
})($j)