JavaScript: Finding HTML DOM Elements
Hello! Welcome to my very first blog post comparing and contrasting JavaScript’s HTML element finding methods. Speaking from experience, I have struggled to understand the core differences between getElementById() vs querySelector() as well as when to use which. So in today’s blog, I will first explain the importance of such methods before diving into more specific advantages and disadvantages.
Importance of Accessing HTML DOM Elements
HTML elements are the building blocks of HTML pages. Often, with JavaScript, you want to manipulate these HTML elements for a variety of reasons. For example, you want your HTML page to be more interactive so you’ve implemented event listeners attached to buttons or text that upon user action, shows different pieces of information. An example of an interactive page would be a basic Harry Potter Database that I’ve worked on using API fetch requests. For more information on my project, feel free to scroll down to the extras section below.
As you can see the page loads new member information upon user click on different Houses as well as each member’s additional personal information upon further clicking into. This is an interactive page utilizing event listeners to display new information upon user interaction with the site. The first step to creating more advanced websites is to understand how to communicate with the DOM and manipulate HTML elements.
To manipulate HTML elements, you have to find the elements first. A couple of ways to do this could be finding HTML elements by id, tag name, class name, CSS selectors, and by HTML object collections.
What is the querySelector() method?
JavaScript’s querySelector() method allows the user to retrieve an element from the DOM or HTML web page using a CSS (Cascading Style Sheets) selector. This method is very versatile because it allows you to select any element from a web page. By using querySelector, the user does not need to worry about only being allowed to select elements by class or IDs. An example of querySelector syntax for getting different elements will be shown below.
document.querySelector(‘p’) // searches for a paragraph tag name document.querySelector(‘.some-class’) // searches for a specific class document.querySelector(‘#some-id’) // searches for a specific ID
It is important to note the the querySelector method returns the first instance of the input it’s given to search for. There is also a querySelectorAll() method that would retrieve all elements that match the inputted tag, class or id.
What is the getElementById() method?
JavaScript’s getElementById() method retrieves an element based on its ID attribute. This method can only retrieve one element from the web page based on its particular ID. This is due to the fact that HTML IDs must be unique, meaning there can’t be multiple elements with the same ID. However, a downside to this method is that it’s much more restrictive then querySelector and can only access elements via their ID. An example of getElementById syntax will be shown below.
document.getElementbyId(‘some-id’) // searches for a specific ID
If the element is not found, the method will return null.
Conclusion
You need to pick the appropriate method for any given task. Both getElementById() and querySelector() methods have their own advantages and disadvantages and therefore neither are “better” than the other. The querySelector() method will go through your entire HTML file, letting you find elements that normally can’t be expressed by getElementById(). However, getElementById() is better supported and more reliable than querySelector(). This because querySelector() is a newer feature and therefore more susceptible to having potential bugs.
The querySelector method lets you retrieve an element using a CSS selector query. The getElementById method retrieves an element by its DOM ID. You should opt to use the querySelector method to select elements with complex rules that can be represented using a CSS selector.
document querySelector method and other ways of getting references to elements in javaScript
In late specs of client side javaScipt there is now the document.querySelector method as well as another method called document.querySelectorAll in the document object in client side javaScript. The query selector method can be used to get a single element by way of an id, class name, or tag name. The query selector all method works in a similar way but can be used to get a collection of elements rather than just one. So these methods are yet another way to go about getting a reference to a single element, or an NodeList that is a kind of array of elements.
For the most part using this method is safe as of this writing, unless for some reason you want to have support for older browsers that are not used that often any more. There are other options that I find myself still using just for the hell of it, for example if I do just want to get an element by id then I still find myself using document.getElementById to do so. Still the querySelector method works well at getting at an element not just by id t, but also in an array of different ways other then that of just an id property value of an element.
I thing that it is not a good idea to get caught up in this nit puck issues though, regardless if query selector is used, or a more tired yet true option, the end result is the same. One way or another I want to gain a reference to an element, or a collection of elements.
1 — The basics of Document.querySelector, and Document.querySelectorAll
If you are familiar with jQuery then you will like document querySelector as a way to gain references to an element. This allows for a wide range of possibilities for gaining accesses to dom elements. An element reference can be obtained by Id, class, and tag name rather than just one of those ways to go about selecting elements such as with the document get element by id method, or the get elements by class name method.
In addition there is also the document querySelectorAll method that works more or less the same as query selector, but as you would expect returns a collection of elements rather that just a single element. The return value of query selector all is a node list rather than an html collection though, but aside from that, and maybe some backward compatibility concerns the method is a good choice for getting a collection of elements.
In this section I will be going over a few quick examples of these methods for starters. I try to always keep these examples as simple as possible, but I still assume that you have at least some background when it comes to getting started with javaScript in general. When I first started out with client side javaScript I was using the file protocol as a way to just open up local files in a web browser, but for many reasons it would be best to set up a basic static web sever and few what one is working on by way of the http protocol. There are other ways of just getting started in a browser though such as using the javaScript console.
The source code example in this post are on github
The source code examples for this post can be found in my test vjs repository. This vanilla javaScript test repository is where I park my source code examples for my many other posts on javaScript that I have written thus far also.
1.1 — Query selector will return a single element reference
The query selector method will return an element reference just like a method such as document.getElementById. This differers from other methods that might return a collection of element references. So if I want to get a reference to an element such as by an id, or any unique value, then the query selector method works just fine. However if I want to get an element reference by way of something such as tag or class name that may present a problem as there will often be more than one element in the dom that will meet that kind of query criteria.
So there are element reference objects, and then there are collections of these such objects. If I do just want an single element reference then maybe the regular query selector method will work just fine. However in most cases I will want to use a method that will give me a collection of elements rather than juts a single element object. With that said on top of the query selector method there is also the query selector all method.
1.2 — Query Selector all will return an NodeList
The query selector all method will not return a single element reference, but an NodeList collection of element or node references. A NodeList is like an array, but it will not have the same prototype methods.
There are two kinds of NodeLists one type is call and alive NodeList where changes to the dom will automatically update the content of the NodeList, the other is an HTML collection that is a kind of live collection of elements. However the kind of NodeList that query selector all returns is a static NodeList.
If you do not care at all about backward compatibility with other browsers that do not support these methods that one can just go ahead and use these methods as a way to get references to elements. Still there are other options when it comes to getting references to elements. I do still find myself using document.getElementById, and not always just because it has better backward compatibility. When I do just want to get an element by way of an id attribute it still woks just fine, and it makes the code more clear.
2 — The tired yet true get element by id method
The tired yet true way of getting a reference to a single element by way of an id attribute is the get element by id method. I do often still find myself using this method as a way of getting a reference to a single element if there is an id for it.
Of course I can also get a single element by way of id using query selector, but as long as this is here there is the added advantage of it still working on older clients. I can not say that it is an issue that concerns me that much these days when I look at the browser stats of this website at least. However I still find myself using this method over all others just for the hell of it anyway.
3 — The tired yet true get elements by tag name
Another option for getting at element references is the get elements by tag name method. This method is like query selector all in the sense that it will return a collection of element references rather than a single element. However it will only get collections by tag name as the same suggests, so it is limited in that regard. However one note worthy difference is that it will return an HTMLCollection rather than a NodeList.
4 — Get an element from a window relative point position
The document get element from point method can be used to get the top most element at a given window relative position. To use this method I just need to call the document.elementFromPoint method and pass the position that I want to check for an element. In the event that there is an element there, it will be returned.
5 — Conclusion
So the document query selector method is one way to go about getting a single element in an HTML document. In addition there is also the query selector all method that can be used to get a collection of elements. One down side is that these methods have not been around as long as other options that there are to work with in client side javaScript, but if your sites browser stats show that it is safe to just go ahead and use them, maybe code will not break for that many visitors.
Another thing to remember is what it is that is returned by these methods. There might be this expectation that the methods that return collections will return an array of elements references and therefor there are array prototype methods like map that can be used with them. This is not the case with HTMLCollections and NodeLists there is a whole separate collection of prototype methods to work with when it comes to these kinds of collections.
Document: querySelector() method
The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.
Note: The matching is done using depth-first pre-order traversal of the document’s nodes starting with the first element in the document’s markup and iterating through sequential nodes by order of the number of child nodes.
Syntax
Parameters
A string containing one or more selectors to match. This string must be a valid CSS selector string; if it isn’t, a SyntaxError exception is thrown. See Locating DOM elements using selectors for more about selectors and how to manage them.
Note: Characters that are not part of standard CSS syntax must be escaped using a backslash character. Since JavaScript also uses backslash escaping, be especially careful when writing string literals using these characters. See Escaping special characters for more information.
Return value
An Element object representing the first element in the document that matches the specified set of CSS selectors, or null is returned if there are no matches.
If you need a list of all elements matching the specified selectors, you should use querySelectorAll() instead.
Exceptions
Thrown if the syntax of the specified selectors is invalid.
Usage notes
If the specified selector matches an ID that is incorrectly used more than once in the document, the first element with that ID is returned.
CSS pseudo-elements will never return any elements, as specified in the Selectors API.
Escaping special characters
To match against an ID or selectors that do not follow standard CSS syntax (by using a colon or space inappropriately, for example), you must escape the character with a backslash (» \ «). As the backslash is also an escape character in JavaScript, if you are entering a literal string, you must escape it twice (once for the JavaScript string, and another time for querySelector() ):
Examples
Finding the first element matching a class
In this example, the first element in the document with the class » myclass » is returned:
Complex selectors
Selectors can also be really powerful, as demonstrated in the following example. Here, the first <input> element with the name «login» ( <input name=»login»/> ) located inside a <div> whose class is «user-panel main» ( <div > ) in the document is returned:
Negation
As all CSS selector strings are valid, you can also negate selectors:
This will select an input with a parent div with the user-panel class but not the main class.
How to Get Element By Class in JavaScript?
I want to replace the contents within a html element so I’m using the following function for that:
The above works great but the problem is I have more than one html element on a page that I want to replace the contents of. So I can’t use ids but classes instead. I have been told that javascript does not support any type of inbuilt get element by class function. So how can the above code be revised to make it work with classes instead of ids?
P.S. I don’t want to use jQuery for this.
12 Answers 12
This code should work in all browsers.
The way it works is by looping through all of the elements in the document, and searching their class list for matchClass . If a match is found, the contents is replaced.
Of course, all modern browsers now support the following simpler way:
but be warned it doesn’t work with IE8 or before. See http://caniuse.com/getelementsbyclassname
Also, not all browsers will return a pure NodeList like they’re supposed to.
You’re probably still better off using your favorite cross-browser library.
That will work in «modern» browsers that implement that method (IE8+).
If you want to provide support for older browsers, you could load a stand-alone selector engine like Sizzle (4KB mini+gzip) or Peppy (10K mini) and fall back to it if the native querySelector method is not found.
Is it overkill to load a selector engine just so you can get elements with a certain class? Probably. However, the scripts aren’t all that big and you will may find the selector engine useful in many other places in your script.
A Simple and an easy way
I’m surprised there are no answers using Regular Expressions. This is pretty much Andrew’s answer, using RegExp.test instead of String.indexOf , since it seems to perform better for multiple operations, according to jsPerf tests.
It also seems to be supported on IE6.
If you look for the same class(es) frequently, you can further improve it by storing the (precompiled) regular expressions elsewhere, and passing them directly to the function, instead of a string.
This should work in pretty much any browser.
You should be able to use it like this:
I assume this was not a valid option when this was originally asked, but you can now use document.getElementsByClassName(»); . For example:
There are 3 different ways to get elements by class in javascript. But here for your query as you have multiple elements with the same class names you can use 2 methods:
getElementsByClassName Method — It returns all the elements with the specified class present in the document or within the parent element which called it.
querySelectorAll Method — It select element on the basic of CSS selectors. Pass your CSS class to it with a dot and it will return all the element having specified class as an array-like object.