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
}
Written by Greg
Related protips
4 Responses
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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Js
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#