Created
October 4, 2014 14:26
-
-
Save cgrymala/85f25766df8d2befa481 to your computer and use it in GitHub Desktop.
Check if an element exists in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Check to see if an element exists in the page | |
* Avoids potential XSS attack outlined in https://eamann.com/tech/jquery-xss/ | |
* @see https://eamann.com/tech/jquery-xss/ | |
*/ | |
function doesElementExist( el ) { | |
try { | |
var tmpLen = document.querySelectorAll( el ).length; | |
if ( 0 < tmpLen ) { | |
return true; | |
} else { | |
/*console.log( 'Element was not found' );*/ | |
return false; | |
} | |
} catch( e ) { | |
/*console.log( 'Element threw an error: ' ); | |
console.log( e );*/ | |
return false; | |
} | |
/*console.log( 'No idea what happened, but no element was returned' );*/ | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment