Monkey Raptor

Friday, December 26, 2014

JavaScript: How to Detect if an Element Exists?

There are events in JavaScript we can use to capture the DOM elements (as variables).
But sometimes, we can't precisely detect when they will be complete (ready for DOM manipulation) using "only" the event (load, DOMContentLoaded, readystatechange, etc). Especially if they are injected dynamically.


Let's

Structure of using setInterval
The JavaScript basic coding looks like this:

Using setInterval with counter (as setTimeout substitute)
This is useful so that the timer won't run infinitely if the element we're looking for isn't actually in the HTML document (we forgot to put the proper name/place the element, or sumthin):


Let's use the basic method (without counter)

#1 Example

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



#2 Example

Working with class
We want to find out the existence of all elements with the class some_class thingy.



That's the basic idea of using the JavaScript setInterval method to detect whether a DOM element (or multiple elements) is (are) ready.

The basics and examples above start right away and self-invoked.
We can also attach an event before the "search" begins. Such as, window.onload.


This is the snapshot of a "simple" demo

I suppose you can re-type this and run on browser.


Informational
To get the DOM elements by tag name, we can use:
document.getElementsByTagName( "the_tag" )

Example:
We want to get all the div tags on the HTML document:
document.getElementsByTagName( "div" )
That will return a set of HTMLCollection. Not an array (of elements).
The HTMLCollection needs to be converted to an array so we can "fully access" any of them.
Related Q&A at Stack Overflow
There are also:
  • document.getElementsByClassName( "the_class_name" ) (HTML5): returns array of elements with the specified class "the_class_name"
  • document.getElementsByName( "the_name" ) (HTML4): returns array of elements with name attribute "the_name"
  • element.getElementsByTagNameNS( "namespaceURI", "the_tag_name" ) (XML/XHTML): info at MDN
JavaScript: How to Detect if an Element Exists?
https://monkeyraptor.johanpaul.net/2014/12/javascript-how-to-detect-if-element.html?m=0

No comments

Post a Comment

Tell me what you think...