Importance of Accessing HTML DOM Elements
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?
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?
document.getElementbyId(‘some-id’) // searches for a specific ID
If the element is not found, the method will return null.
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.
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.
The source code example in this post are on github
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
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.
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.
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.
Thrown if the syntax of the specified selectors is invalid.
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
Finding the first element matching a class
In this example, the first element in the document with the class » myclass » is returned:
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:
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.
I want to replace the contents within a html element so I’m using the following function for that:
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:
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.