Skip to content

Instantly share code, notes, and snippets.

@cgrymala
Created October 4, 2014 14:26
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Check if an element exists in JavaScript
/**
* 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