0

I would like to test if an element exists but i cannot do it with $('#id')length > 0 because i am testing an input element which might not contain any characters and then it results in 0 even if it exists...

How can i test if this element exists??

1
  • What are you trying to achieve? If you are testing element exist to show/hide or any jQuery operations, then simply use $('#id').show() because jQuery internally will call the function only if it finds one or more matching elements. Commented May 11, 2012 at 18:07

3 Answers 3

2

length property is not returning the characters in the element. but the number of elements in the jQuery object. So you should be good to use length property in your case.

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

Comments

1

there is a typo in the code!?

$('#id').length > 0

4 Comments

Actually im just getting tired... and i put .val() automatically in my code -.- It works now ty..
See it is not a typo in code, I think he wanted to test if an input elements has empty values.
nono i wanted to test if element exists but because i been coding .val() all night I automatically put .val() after it.. and then i coundnt see it staring right at it... I will accept this answer as soon as i can
@vega yes, it sounds that is not a typo, length of an id is weird. if ($("#id").text() != "")?
1

Do it like this, Demo on JsFiddle

With jQuery

$('#id').length > 0

With Javascript

if(document.getElementById('ID') != null)
{
    alert("Element found");
}

2 Comments

This is not correct as $('Anything') always returns jQuery object. It is never null. -1 >> jsfiddle.net/skram/RewrK <<
Your are right @Vega. I have corrected my answer please have a look

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.