1

I was going to do $("#foo") !== null to assert that an element with the id="foo" does exist in the page, but it turns out even if the element doesn't exist, the selector $("#foo") still returns an object.

So to test whether the selector can find an element, should

assert($("#foo").length >= 1);

be used? I also thought of using assert($("#foo").is("div") but if the HTML is changed, and the element is not a div but becomes a p or span, then it will break the assert. What is a good, standard way to assert that the element does exist?

jsfiddle sample: http://jsfiddle.net/qnbAn/1/

nonopolarity
  • 146,324
  • 131
  • 460
  • 740

4 Answers4

1

Why not just:

if ($("#foo").length){
    // element with id foo existed
}

Since id of an element is unique.

Eli
  • 14,779
  • 5
  • 59
  • 77
0

Yes, you should use length to check if a given selector matches anything.

Selectors that match nothing result in empty jQuery objects, but even empty jQuery objects are valid instances and evaluate to true in a boolean context.

Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
0

Use

$('#elementId').Length > 0

like

Is there an "exists" function for jQuery?

Community
  • 1
  • 1
Saeed Afshari
  • 939
  • 1
  • 9
  • 17
0

Do this in simple like this

if($("#mydiv").length){
 // mydiv exist
}
rajesh kakawat
  • 10,826
  • 1
  • 21
  • 40