0

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 ?

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
Andrew
  • 3
  • 1
  • 2
  • See this question http://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery – Catfish Mar 26 '10 at 19:21

4 Answers4

5

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
  • 623,446
  • 136
  • 1,297
  • 1,155
  • That's a good point, jQuery doesn't throw if the return value is empty, it just doesn't do anything. – technophile Mar 26 '10 at 19:13
  • hey thanks - but if I want to try and "find and if cant find do nothing" how do I do this ? – Andrew Mar 26 '10 at 19:17
  • @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 Mar 26 '10 at 19:19
  • Andrew, you missed what Nick & technophile said. The "foo is not a function" error is thrown because jQuery is not included correctly. If a jQuery selector finds no matched elements, it returns an empty jQuery object and no errors are thrown on chained function calls. – Matt Ball Mar 26 '10 at 19:21
1

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
  • 8,195
  • 4
  • 41
  • 41
0
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
  • 27,253
  • 7
  • 76
  • 97
0

You can check the return value's length property:

var myElement = $('.class');
if (myElement.length > 0)
    myElement.css(random_stuff);
technophile
  • 3,556
  • 1
  • 20
  • 24