Skip to content

Instantly share code, notes, and snippets.

@cgrymala
Created October 4, 2014 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cgrymala/85f25766df8d2befa481 to your computer and use it in GitHub Desktop.
Save cgrymala/85f25766df8d2befa481 to your computer and use it in GitHub Desktop.
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