CSS3, HTML, JavaScript, Programming, Web Development

A Basic Look at using the JavaScript QuerySelector Function with CSS Selectors

JavaScript QuerySelector
JavaScript QuerySelector

The JavaScript querySelector (and the related querySelectorAll) functions give you a lot of control over elements on your page since these functions support using CSS Selectors. You can target elements on your page in a number of different ways using CSS selector syntax which will likely save you a lot of time and effort. As well, the power of using CSS Selectors in JavaScript makes it less necessary to start referencing more heavy-weight libraries such as JQuery for doing simple DOM manipulations.

As you can see from the image of my example page to the left, I haven’t put much effort into making the example very friendly to the eye, but look and feel isn’t what this is about. The main point of this example is to test getting elements on the page using a variety of CSS Selectors in a JavaScript QuerySelector function when the user clicks one of the buttons. The value of the selected element is then alerted out to the user.

I’ll post the full example code for the example page at the bottom of this article. The sample page could be of some use to anyone wanting to test some functionality quickly.

For starters, you should note that if you use the JavaScript querySelector function, it will return the first matching element to you. If you want a collection of matching elements, then you’ll need to use the related JavaScript querySelectorAll function. Like I mentioned at the start of this article, the querySelector function uses CSS Selector syntax (including some Regular Expression – like functionality) that really gives your DOM searches a boost from other element selectors such as document.getElementById or even the more flexible document.getElementByCSSClass and getElementsByTagName.

If you are interested in reading more about useful CSS Selectors, then have a look at the tuts+ article I’m linking.

Example 1: getting an element using both querySelector and getElementById by CSS class and element type

In this example you can see how to user getElementById first to narrow down the possible set of elements for querySelector to search by using the following syntax:

var firstTextBox = document.getElementById('PageFooterTable').querySelector('input.firstCheckBox')

The getElementById portion of the statement narrows down the list of searchable elements to just those contained within the table element called PageFooterTable. Once we have narrowed the search, we use CSS Selector syntax to find the element we want to work with using: input:firstCheckBox. What this syntax means is that querySelector will look for the first input element of the CSS class firstCheckBox that is contained in the table element.

Example 2: getting an element using both querySelector and getElementById by to get the element by id

Here we are using a slight variation of the method we used in example 1 above. As before, we narrow down our search to a specific table element on the page by using getElementById. Then we get an element contained in that table directly by Id using the #txtSecondTextBox. The hash symbol in front of the id of the element to find is CSS selector syntax for addressing elements by id. Here is the line in question:

var secondTextBox = document.getElementById('PageFooterTable').querySelector('#txtSecondTextBox')

Example 3: using querySelector to find the first element on the page of a specific type

This example shows how to use a CSS selector to get the first element on the page by type. In this case, we are looking for the first input type element.

var secondTextBox = document.querySelector('input')

Example 4: CSS Selector syntax for finding a nested element

This example builds a bit on Example 3 above. Instead of looking for the first input element on the page, we are telling the CSS Selector to look for the first input element on the page that is nested in a span element. Useful stuff, but wait, it gets even better.

var secondTextBox = document.querySelector('span + input')

Example 5: Using regular expression type CSS Selector syntax to search for elements starting with a particular value

In this example we’ll search through the Web page for the first instance of an input element that has a text value starting with a particular word. It’s pretty amazing that one can do this. Here is how to search for an input element with a value starting with the word: First:

var firstTextBox = document.querySelector('input[value*="FIRST"]')

Example 6: Using regular expression type CSS Selector syntax to search for elements ending with a particular value

Seeing as how in Example 5 above, we selected an input element on the page by starting value, it makes sense that we should also be able to search by partial ending value. As you might expect from regular expression syntax, searching by the ending value involves using the $ sign. Here’s how to search for the first input element on the Web page that has a value ending with the words: CSS Class:

var firstSpan = document.querySelector('input[value$="CSS Class"]')

Example 7: Searching the Web page for the Nth element of a particular type

CSS Selector syntax also lets you do this really neat trick. You can look for the Nth instance of a particular type of element on your page. Note that this is not zero-based.  In this example, we are looking for the second instance of an input element on the page:

var secondInput = document.querySelector('input:nth-of-type(2)')

Seems straightforward enough. One important thing to note is that this search looks for the Nth element only at the level specified… in this example right beneath the document node. That means that the selector will ignore elements nested within other page elements such as, for example, input elements contained within a table element. You’ll need to remember to be very specific in narrowing down where on the page the set of elements is that you want to get the Nth of when using this selector.

Example Page Code

In case you want a simple example page showing the concepts I’ve reviewed in this blog post, or even if you just want to see an example of how it fits together, below is the code for the example page. As I explain in the article above, each button click will call a JavaScript function that will alert the output of using querySelector to find particular Web page elements using CSS Selector syntax.

<html>
<head>
<script>
function testFirstQuerySelector(){
var firstTextBox = document.getElementById('PageFooterTable').querySelector('input.firstCheckBox')
alert(firstTextBox.value);
}
function testSecondQuerySelector(){
var secondTextBox = document.getElementById('PageFooterTable').querySelector('#txtSecondTextBox')
alert(secondTextBox.value);
}
function testThirdQuerySelector(){
var secondTextBox = document.querySelector('input')
alert(secondTextBox.value);
}
function testFourthQuerySelector(){
var secondTextBox = document.querySelector('span + input')
alert(secondTextBox.value);
}
function testFifthQuerySelector(){
var firstTextBox = document.querySelector('input[value*="FIRST"]')
alert(firstTextBox.value);
}
function testSixthQuerySelector(){
var firstSpan = document.querySelector('input[value$="CSS Class"]')
alert(firstSpan.value);
}
function testSeventhQuerySelector(){
var secondInput = document.querySelector('input:nth-of-type(2)')
alert(secondInput.value);
}
</script>
</head>
<body style="background-color:white;">
Page to test CSS Selectors with the JavaScript QuerySelector Function<br>
<input type="text" value="TOP TEXTBOX">
<table id="PageFooterTable">
<tr>
<td>
<input type="text" id="txtFirstTextBox" value="FIRST TEXTBOX TEXT" class="firstCheckBox">
</td></tr>
<tr>
<td>
<span id="spanSecondTextBoxLabel">Second Text Box span</span>
<input type="text" id="txtSecondTextBox" value="SECOND TEXTBOX TEXT" class="secondCheckBox">
</td></tr>
</table>
<input type="button" onClick="testFirstQuerySelector();" value="Click here to test QuerySelector() by First element CSS Class: querySelector('input.firstCheckBox')"><br>
<input type="button" onClick="testSecondQuerySelector();" value="Click here to test QuerySelector() by Second element ID: querySelector('#txtSecondTextBox')"><br>
<input type="button" onClick="testThirdQuerySelector();" value="Click here to test QuerySelector() by first input element on page: querySelector('input')"><br>
<input type="button" onClick="testFourthQuerySelector();" value="Click here to test QuerySelector() by Adjacent input element on page: querySelector('span + input')"><br>
<input type="button" onClick="testFifthQuerySelector();" value="Click here to test QuerySelector() to get the element by partial input area value: querySelector('input[value*='FIRST']')"><br>
<input type="button" onClick="testSixthQuerySelector();" value="Click here to test QuerySelector() to get the element by partial Id ending value: querySelector('input[value$='FIRST']')"><br>
<input type="button" onClick="testSeventhQuerySelector();" value="Click here to test QuerySelector() to get the element by count on page: querySelector('input:nth-of-type(2)')"><br>
</body>
</html>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s