0

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 !

6
  • $j(this).css('background-image') === 'url(http://daddykate-acc.daddykate.be/wp-content/plugins/js_composer/assets/vc/vc_gitem_image.png)' ....................................................... check value of top.location.pathname and $j(this).css('background-image') Commented Jul 28, 2016 at 8:50
  • If you use console.log($j(this).css('background-image')), what do you get? Seems obvious to debug, right?! Commented Jul 28, 2016 at 8:52
  • The console.log returns none for some weird reason, maybe because dom has not loaded yet? @A.Wolff Commented Jul 28, 2016 at 9:00
  • It is being generated by the WP plugin when you don't add an image to your post. I'll investigate. @A.Wolff Commented Jul 28, 2016 at 9:05
  • So you have to run your snippet once the plugin has updated the DOM, not before. How to? It depends which plugin you are talking about Commented Jul 28, 2016 at 9:07

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.