Last Updated: February 25, 2016
·
1.752K
· gregbenner

JS / JQuery: Check if an Element exists

Need to know if you are on a certain page homepage and if so execute some JS?

if ( $(".homepage").length) {
//code
}

4 Responses
Add your response

For clarity you can also add it to jQuery

   $.fn.exists = function () {
  return this.length !== 0;
}

and then simply -> $(".homepage").exists()

over 1 year ago ·

I usually do things like that :

fname : function() {
if(!$('.classname').length) return;
}

over 1 year ago ·

I don't use jQuery that much anymore in favour of Angular but I think a bit better than my code from 2 years ago would be to store all your jQuery selectors to variables then check truthy value like:
var homePage = $('.homepage')
if(homePage) { //code}

over 1 year ago ·

Looks good but you don't need "!== 0;" just ".length" checks this.

over 1 year ago ·