find out if an element exists in javascript

To find out if an element exists in JavaScript, you can use various methods. One of the most common methods is to use the querySelector method if you want to select an element by its CSS selector.

index.tsx
if (document.querySelector('#myElement') !== null) {
  // The element exists
} else {
  // The element doesn't exist
}
119 chars
6 lines

Alternatively, you could use getElementById or getElementsByClassName methods depending on how you want to select the elements.

index.tsx
if (document.getElementById('myElement') !== null) {
  // The element exists
} else {
  // The element doesn't exist
}

if (document.getElementsByClassName('myClass').length > 0) {
  // At least one element with 'myClass' exists
} else {
  // No elements with 'myClass' exist
}
278 chars
12 lines

Note that the getElementsByClassName method returns an HTMLCollection, so you need to check its length property to know if any element with the specified class exists.

related categories

gistlibby LogSnag