2

I need to see if an object is present on the page by its selector.

This WOULD normally do it:

startpageentry = $('#' + startpageid)

But that doesn't return anything. I need a boolean I can put into an if statement like this:

if (startpageentry != 'false') {}

How can I do this?

alt
  • 13,357
  • 19
  • 80
  • 120
  • see http://stackoverflow.com/questions/299802/how-do-you-check-if-a-selector-exists-in-jquery – John Pick Mar 06 '12 at 07:41
  • Was 'false' a typo? You should compare to false, not 'false'. Or, if you know it's a boolean, you should compare with !== false. (Or just !startpageentry) – Corbin Mar 06 '12 at 07:44

3 Answers3

5

Use length:

var startpageentry = $('#' + startpageid).length;

To store boolean result, use:

var isPresent = $('#' + startpageid).length > 0;

Now isPresent will be true if it exists false otherwise.

Or simply:

if ($('#' + startpageid).length){
  // exists
}
else {
  // does not exist
}
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
3

There is no boolean for that because it would prevent from chaining.
You could use $(something).length>0.
But if you need to run in over and over again, I made a little jQuery plugin which is called doesExist()

/* doesExist PLUGIN (c) MS */
/* (c) Michael Stadler(MS), */
(function($){
$.fn.doesExist = function()
{
return jQuery(this).length > 0;
};
})(jQuery);

The usage of it would be

if($('#something').doesExist()){
      //doesExist returns a boolean
}
mas-designs
  • 7,498
  • 1
  • 31
  • 56
2

To get a Boolean with jQuery...

var startpageentry = !! $('#' + startpageid).length;

Without jQuery...

var startpageentry = !! document.getElementById(startpageid);

Of course, you don't really need a Boolean to test it. You could just rely on 0 being falsey (for the jQuery version) or null being falsey (for the non jQuery version).

Also, your but that doesn't return anything isn't correct. It would return a reference to the jQuery object returned. Objects in JavaScript are always truthy, so testing it in a condition won't tell you if the selector matched any elements or not.

alex
  • 479,566
  • 201
  • 878
  • 984