简体   繁体   中英

Check if an object exists by its selector, return a boolean value with jQuery or Javascript

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?

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
}

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
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM