Skip to main content

JavaScript: How to Detect if an Element Exists?

There are events in JavaScript as reference before we start to capture the DOM element: load or DOMContentLoaded or readystatechange, etc.

But sometimes, we can't solely depend on either one of those events to detect when the elements have been ready (available) for further DOM manipulation.

Especially if the element is injected dynamically.


So to answer that, we can use setInterval to wait and repetitively search the particular element(s) we need to find.

Using setInterval

Let's wrap it with anonymous auto-invoked function.

Limiting setInterval with Counter

This is useful so that the timer won't run forever if the element is never to be found:


Let's use the timer without the counter limiter and dive into the searching methods to get the element.


#1 Working with id

It can be done by using getElementById.

For instance, we want to find an element with the id element-id.


#2 Working with class

It can be done by using querySelector for just 1 element. If there are multiple elements with similar class in DOM, the first found from the NodeList will be returned.

For instance, the class of the element is .single-class.


#3 Working with multiple elements with similar class

It can be done by using querySelectorAll for multiple elements. This method will return NodeList. I put spread syntax assignment ([...]) to automatically convert it to Array.

For instance, the class of the element is .similar-class.


The Methods querySelector and querySelectorAll to Get the Element(s)

querySelector will return the DOM element and querySelectorAll will return the NodeList.

To convert NodeList into Array, so it will be iterable using reduce, map, filter, etc., we can implement [...NodeList] ➡️ Spread syntax. Just like the example above and more examples below.

Side note:

NodeList can use forEach method since July 2015.

Both querySelector and querySelectorAll can be used to get element by id

We need to put # (hashtag) in front of the element's id name to do it.

So the id of an element with id = element-id must be written as #element-id like so:

Both can be used to get element by its native tag, like div, p, a, etc.
Both can be also used to get element by its specific attribute.

For example we want to find all a with attribute target="_blank":


Combine with Event

Instead of using anonymous auto-invoked function, we can wrap it with event listener ➡️ addEventListener.

DOMContentLoaded event:

load event:


Thank you for visiting.

I hope this is useful 🙂

SEARCH
Last modified on

Comments

Monkey Raptor uses cookies or biscuits 🍪 for analytics, functionality, and advertisements. More info in Privacy Policy