Skip to content

October 14, 2014

How to select elements of page without jQuery

How to select element on page without jQuery

In some cases using of libraries such jQuery is impossible, so we should use just JavaScript. How to select elements of page without jQuery?

We have several options if we want select element using JavaScript. Of course the most well-known way is to use document.getElementById (select element with ID attribute), but as usual in html markup CSS-classes are more common things than IDs.

Another option is getElementByTagName, it has good support across browsers but it’s not really usefull for real projects with a lot of similar tags and different CSS-classes.

We can choose getElementsByClassName, but it will not work for us if we still have to support IE8.

Great option for those who supporting IE8 and above is querySelectorAll. This method will return a list of nodes which matches your selector. This method supports in IE8 only CSS2 selectors, in browsers from IE9+, Chrome, Firefox and Safari we can use sintax similar to jQuery selectors!

Let’s look to the example of using this method:

We have four div elements, two of them with correct ID and correct CSS class, and another two elements has wrong class and ID. The last div is for printing our results of calculation correct elements.

Here we have two lines of JS code – the first one is for selecting correct elements through our DOM, using syntax similar to jQuery.
var correctElements = document.querySelectorAll('#correctID, .correct-class');

The second line of code is for printing results of calculation of correct elements – method returns us an array with elements and we just getting the length of this array to know how many correct element on the page we have, and put this number in html (innerHTML) of <div class="result">, which was selected by querySelectorAll method document.querySelectorAll('.result'), and we choose it like the first element of returned array [0].
document.querySelectorAll('.result')[0].innerHTML = correctElements.length;

The result page shows us all five block elements:

As we can see, method querySelectorAll works perfectly and our results are correct.