Welcome to WebmasterWorld Guest from 54.198.52.82

Forum Moderators: open

jQuery, run only if element exists

.on('load',...) or .length

     
1:04 am on Jun 30, 2018 (gmt 0)

Senior Member

WebmasterWorld Senior Member 5+ Year Member Top Contributors Of The Month

joined:Mar 15, 2013
posts: 917
votes: 77


I only want a function to run if an element exists on the page... which would you guys do, and why?

if ($(element).length) {
// do this
}

$(element)
.on('load', function() {
// do this
});
2:16 am on July 17, 2018 (gmt 0)

Senior Member from US 

WebmasterWorld Senior Member jab_creations is a WebmasterWorld Top Contributor of All Time 10+ Year Member

joined:Aug 26, 2004
posts: 3178
votes: 22


Use pure JavaScript so you don't put an artificial death-clock on your code. Feel free to browse the JavaScript functions in the documentation of my website in my profile.

if (id_('example')) {alert('the element exists!');}


function id_(id)
{
if (id == '' && window['console']) {console.log('Developer: empty id called from: '+id_.caller.toString().split('function ')[1].split('(')[0]);}
return (document.getElementById(id)) ? document.getElementById(id) : false;
}
1:06 am on July 19, 2018 (gmt 0)

Junior Member

joined:Jan 13, 2014
posts:115
votes: 23


if ($(element).length > 0) {
// do this
$(element)
.on('load', function() {
// do this
});
}
 

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members