Earlier today, a student in my private Discord server asked for the best way to detect if an element exists or not before running more code.
Quick aside: if you want to join my Discord and get friendly, personalized answers to your web dev questions, you get FREE access when you sign up for one of my courses.
If you use a selector method (like querySelector()
or getElementById()
), and the element you're looking for isn't found, the method returns null
. Since that's falsy, you use a simple if
check to see if the element exists or not.
// Try to get the element let elem = document.querySelector('#nope'); // If it exists, do stuff... if (elem) { // Do code! }
If you want to be even more explicit, you can cast the element to a boolean using the bang operator (!
) twice.
This runs an "if not" type check, then reverses it, creating an "if true" condition.
// If it exists, do stuff... if (!!elem) { // Do code! }
I have seen code that explicitly checks for undefined
or null
in the wild before, but in my experience, doing this is not neccessary.
if (typeof(elem) !== 'undefined' && elem !== null) { // Do code... }
What if you're getting back a collection of elements instead of just one?
For that, you can check if the collection has a length
.
// Try to get a collection of elements let elems = document.querySelectorAll('.nope'); // If they were found, do stuff... if (elems.length) { // Do code! }
Alternatively, you can just run your loop as-is.
Methods like querySelectorAll()
return an empty NodeList if no items were found, so your loop will run 0
times anyways.
// If there are no items in elems, this just won't run for (let elem of elems) { // Do code! }
I have a favor to ask. If you enjoyed this email, could you forward it to someone else who you think might also like it, or share a link to my newsletter on your favorite social media site?
Cheers,
Chris
Want to share this with others or read it later? View it in a browser.
0 Komentar untuk "[Go Make Things] How to check if an element exists with vanilla JavaScript"