53

I currently do this to check if one of two elements exists:

if ($(".element1").length > 0 || $(".element2").length > 0) { //do stuff... } 

Is there a better way to rewrite the same? I mean, is .length the same as .length > 0?

1
  • You might find this question answers your question. Commented Dec 14, 2009 at 5:43

7 Answers 7

47
if ($(".element1").is('*') || $(".element2").is('*')) { // code } 

EDIT (per comment) Select elements by multiple classes in one call:

if ($(".element1, .element2").is('*')) { // code } 
Sign up to request clarification or add additional context in comments.

4 Comments

Note that you can also combine the two selectors into one like so: $(".element1, .element2").
Is ".is()" the same as ".length > 0"? Whats the difference, if any?
Nimbuz, good post on use of .is() - bennadel.com/blog/…
The SO Question Vincent linked to covers the topic thoroughly - good read.
25
if ( $('#myDiv')[0] ) { //do something } 

..works best!

Found here.

Comments

16

All jQuery elements have the .length property. You can just go:

if ($('img').length) // Implies: If this element exists.. 

http://jqueryfordesigners.com/element-exists/

Comments

2
!$.isEmptyObject($.find('#urId')) 

this will return "true" if the element exists and False if not

cheers :)

Comments

1

Just use .each().

$(".element1").each(function(){ //Do Something here } 

Simple...

Comments

1

See Extremely updated version of this plugin here! Now uses callback function so you can maintain chainability if you choose. Can completely replace if statement or can still be used within if statement


You could create a very simple jQuery plug-in for this, as such:

jsFiddle

(function($) { if (!$.exist) { $.extend({ exist: function(elm) { if (typeof elm == null) return false; if (typeof elm != "object") elm = $(elm); return elm.length ? true : false; } }); $.fn.extend({ exist: function() { return $.exist($(this)); } }); } })(jQuery); 

USE

// With ID $.exist("#eleID"); // OR $("#eleID").exist(); // With class name $.exist(".class-name"); // OR $(".class-name").exist(); // With just tag // prolly not best idea aS there will be other tags on site $.exist("div"); // OR $("div").exist(); 

With your If statement

if ($(".element1").exist() || $(".element2").exist()) { ...stuff... } 

Of course this plugin could be further extended to be much more fancy (handling multiple calls at once, creating non-existing elements based on a pram), but as it stand now, it does a very simple, very needed function ... Does this element exist? return True or False

jsFiddle

Comments

1
$.fn.exists = function(ifExists) { return this.length ? ifExists.call(this, this) : this; }; 

usage:

$('.element1, .element2').exists(function(els) { // this and els refers to $('.element1, .element2') }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.