0

Maybe I miss something but anywhere I read it is suggested that if I want to check whether a jQuery constructor returns a jQuery object is done by:

if(jQuery('.something').length){...}

but how would I validate if it is an html element in the jQuery object that it returns?

what I mean is that this also returns true:

if(jQuery(44551).length){...}

although it returns jQuery object it doesn't have html element in it.

2
  • jQuery's selectors return only HTML elements. Commented Aug 28, 2017 at 8:43
  • but what if I provide a number to the jQuery constructor, it won't return html element. Commented Aug 28, 2017 at 8:50

2 Answers 2

2

You could use is() to check if the collection contains an element matching a certain selector

var someelement = $(....); // unknown

if ( someelement.is('.something') ) {...

Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.

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

1 Comment

ok that solves my problem. $('.never-mind').is('.never-mind') returns true (of course after validating that .never-mind exists), and $(555).is(555) returns false. thank you mate
0

To check if there are html elements inside a jQuery element, then do:

if ( $('.el').html().length ) { ...

1 Comment

if I provide a number to the jQuery selector your code throws an error, I could wrap it in a try-catch statement, but @adeneo's solution is simpler. thanks though.

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.