Forum Moderators: open

Message Too Old, No Replies

jQuery, run only if element exists

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

         

csdude55

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

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



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
});

JAB Creations

2:16 am on Jul 17, 2018 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



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;
}

3zero

1:06 am on Jul 19, 2018 (gmt 0)



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