user1432124
user1432124

Reputation:

Check presence of an element with jquery

I have a page in which i need to check the presence of a HTML element dynamically.Therefore I need to know the correct way of doing this

Upvotes: 2

Views: 705

Answers (3)

akim
akim

Reputation: 8759

Personally I like very much the "presence" idiom from Ruby on Rails, so I have added this to my JS set up:

jQuery.fn.presence = function presence() {
    return this.length !== 0 ? this : null;
};

and now use this in my code:

if (el.presence()) { ... }

and better yet

const ul = el.parents('UL').first().presence() ?? el.siblings('UL').first()

(If you can't afford ??, || would do just as well here.)

Upvotes: 0

Juan G. Hurtado
Juan G. Hurtado

Reputation: 2137

You could do:

$(function() {
  if ($('.myElement').length > 0) {
    console.log('There is one or more elements with class="myElement"');
  }
});

Upvotes: 3

Robert Merten
Robert Merten

Reputation: 221

$('#id').length === 0; // element does not exist 
$('#id').length > 0; // element exists 

Upvotes: 2

Related Questions