Skip to content

Instantly share code, notes, and snippets.

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
* @see
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
You can’t perform that action at this time.