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 ?

1

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

That's a good point, jQuery doesn't throw if the return value is empty, it just doesn't do anything.
hey thanks - but if I want to try and "find and if cant find do nothing" how do I do this ?
@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);
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.
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.

Comments

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:

2 Comments

While this is accurate, it's an entirely superfluous check :)
And while it's right 0 is falsy, I think it is still worth putting the extra > 0 for readability :)
0

You can check the return value's length property:

var myElement = $('.class');
if (myElement.length > 0)
    myElement.css(random_stuff);

1 Comment

cool so if I wanted to "find and if cant find do nothing" how would I do this :) ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.