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.
- More aboute
setInterval()
at MDN
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 useforEach
method since July 2015.
BothquerySelector
andquerySelectorAll
can be used to get element byid
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, likediv
,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"
:
-
More about
querySelector()
at MDN -
More about
querySelectorAll()
at MDN
Combine with Event
Instead of using anonymous auto-invoked function, we can wrap it with event listener ➡️ addEventListener
.
DOMContentLoaded
event:
load
event:
- More aboute
document
at MDN - More aboute
window
at MDN
Thank you for visiting.
I hope this is useful 🙂
Comments
Post a Comment