views:

247

answers:

5

Hi Guys,

I am trying to use jQuery to basically wrap a bunch of CSS modifications via jQuery but on pages where the #IDs or Classes dont exist I get errors ? Like

jQuery(".class").css(random_stuff) is not a function

Any ideas what I can do to either "find" the elements and do nothing or ?

A: 
if(jQuery(".class").length)
{
  jQuery(".class").css(random_stuff);
}

per Jquery Faq

You can use the length property of the jQuery collection returned by your selector:

Matthew Vines
While this is accurate, it's an entirely superfluous check :)
Nick Craver
And while it's right 0 is falsy, I think it is still worth putting the extra `> 0` for readability :)
Chetan Sastry
+5  A: 

In this case it looks like the jQuery library isn't being included correctly.

If jQuery finds nothing matching your selector, nothing will happen because it didn't find any elements to perform the action on, this is the default behavior.

Nick Craver
That's a good point, jQuery doesn't throw if the return value is empty, it just doesn't do anything.
technophile
hey thanks - but if I want to try and "find and if cant find do nothing" how do I do this ?
Andrew
@Andrew the default chaining does this: `jQuery(".class").css(random_stuff)` nothing else...your error is the jQuery library not being included in the page properly. Try `alert(window.jQuery);`
Nick Craver
Matt Ball
A: 

You can check the return value's length property:

var myElement = $('.class');
if (myElement.length > 0)
    myElement.css(random_stuff);
technophile
cool so if I wanted to "find and if cant find do nothing" how would I do this :) ?
Andrew
A: 

Sounds like you are missing a reference to jQuery on those pages. jQuery only performs an action on the matched selection...it will not throw an error if nothing matches.

Bradley Mountford