Prior to HTML5, the support for querying elements of a web page was very restrictive. This resulted in web developers having to write targeted code to retrieve Element nodes from the Document Object Model (DOM) by passing node identifiers like ID, ClassName, Name, TagName and namespace.
The APIs used in pre-HTML days were:
· document.getElementById
· document.getElementsByClassName
· document.getElementsByName
· document.getElementsByTagName
· document.getElementsbyTagNameNS
Let us explore the document.getElementbyId in more detail. This API can be used to get a handle to an element by passing in an element ID. This would not work on a group of elements with the same ID, since the handle would be point to a single element only.
To make it better, the HTML5 specification introduced new selector APIs that allowed better queries.
The HTML5 specification says….
To quote the specification,
The HTML5 specification provides methods for selecting and testing elements based on whether or not they match a given selector. With these methods, it is easier to match a set of Element nodes based on specific criteria, than having to subsequently filter the result of calling other methods like getElementsByTagName().
The interface definition of these APIs is
partial interface Document {
Element? querySelector(DOMString selectors);
NodeList querySelectorAll(DOMString selectors);
};
partial interface DocumentFragment {
Element? querySelector(DOMString selectors);
NodeList querySelectorAll(DOMString selectors);
};
partial interface Element {
Element? querySelector(DOMString selectors);
NodeList querySelectorAll(DOMString selectors);
};
This implies that “document” now supports querying by a selector string and returning one element (via document.querySelector) or multiple elements (via document.querySelectorAll)
The document.querySelector API returns the first element which matches the specified DOM string, whereas document.querySelectorAll API returns all the elements which match the specified DOM string.
Hands On
Let us write a simple HTML5 web page which demonstrates how to use the selector APIs.
For this demo, we will create a simple web page and create a unordered list. We will associate each row of the list with a class, either “odd” or “even”. We will use selector APIs to access the rows and control how they look.
Our list is defined as
<ul id=”dataList“>
<li class=”odd”>Odd 1</li>
<li class=”even”>Even 1</li>
<li class=”odd”>Odd 2</li>
<li class=”even”>Even 2</li>
<li class=”odd”>Odd 3</li>
</ul>
To access the first row in the datalist belonging to odd class, we will call the selector API document.querySelector() and pass it the argument that identifies the odd row, in our case it is will be “li.odd”.
To get the first even row, our query selector will be “li.even” and we will call document.querySelector API.
To get all the rows which match the query selector, we will call document.querySelectorAll API.
Now, let us build a complete web page which shows this in action. The code snippet is listed below.
<!DOCTYPE html>
<html>
<meta charset=”utf-8″>
<title>Selector sample</title>
<body>
<button id=”buttonSelectFirstOddRow“ type=”button” onclick=”buttonSelectFirstOddRow_click()“>Select First Odd Row</button>
<button id=”buttonSelectFirstEvenRow“ type=”button” onclick=”buttonSelectFirstEvenRow_click()“>Select First Even Row</button>
<button id=”buttonSelectAllOddRows“ type=”button” onclick=”buttonSelectAllOddRows_click()“>Select All Odd Row</button>
<button id=”buttonSelectAllEvenRows“ type=”button” onclick=”buttonSelectAllEvenRows_click()“>Select All Even Row</button>
<button id=”buttonSelectAllRows“ type=”button” onclick=”buttonSelectAllRows_click()“>Select All Rows</button>
<article>
<header>
<h1>Selector API sample</h1>
<p>Demo showing how to use HTML5 selector API</p>
</header>
<ul id=”dataList“>
<li class=”odd”>Odd 1</li>
<li class=”even”>Even 1</li>
<li class=”odd”>Odd 2</li>
<li class=”even”>Even 2</li>
<li class=”odd”>Odd 3</li>
</ul>
<footer>
<h1></h1>
<p>HTML Goodies</p>
</footer>
</article>
<script type=”text/javascript“>
function buttonSelectFirstOddRow_click()
{
var selectedRow = document.querySelector(‘li.odd‘);
selectedRow.style.color = ‘Red’;
}
function buttonSelectFirstEvenRow_click()
{
var selectedRow = document.querySelector(‘li.even‘);
selectedRow.style.color = ‘Green’;
}
function buttonSelectAllOddRows_click()
{
var selectedRows = document.querySelectorAll(‘li.odd‘);
for (var i = 0; i < selectedRows.length; i++)
selectedRows[i].style.color = ‘Red’;
}
function buttonSelectAllEvenRows_click()
{
var selectedRows = document.querySelectorAll(‘li.even‘);
for (var i = 0; i < selectedRows.length; i++)
selectedRows[i].style.color = ‘Green’;
}
function buttonSelectAllRows_click()
{
var selectedRows = document.querySelectorAll(‘li.odd, li.even‘);
for (var i = 0; i < selectedRows.length; i++)
selectedRows[i].style.color = ‘Pink’;
}
</script>
</body>
</html>
The above code snippet is also available as a download from here.
When you run this webpage in the latest version of your browser (IE, Firefox and Chrome), you can see the selector API in action by clicking on the buttons and seeing the rows change color.
Summary
In this article, we learned about the HTMl5 selector APIs. I hope you have found this article useful.
Are you a game developer looking to jump into the futuristic world of virtual reality? If so, you will likely need to use VR game development platforms and tools to help you along the way, and here is a list of some of the best of the bunch to get you started. After reading this […]
While it is possible to create websites in the modern era using content management systems (CMS) like WordPress and website builder platforms like Shopify, it never hurts to learn the cornerstones of those web development tools, especially if you ever want to add your own custom functionality to your websites. What’s more, not every […]
The images in a web page make the page much more attractive, descriptive, and help improve user experience. In this web development tutorial, we will talk about how to work with images in HTML, and, specifically, background images, inline images, image insertion paths, and the most important attributes of the HTML tag. We will […]
Since the Internet first broke on to the scene in the late 80s and 90s, it has undergone a couple of significant changes, encapsulated by Web 1.0 and 2.0. Now, we are entering into the third version of the Web known as Semantic Web or Web 3.0. In this web development tutorial, we will explore […]
The original home of HTML tutorials. HTMLGoodies is a website dedicated to publishing tutorials that cover every aspect of being a web developer. We cover programming and web development tutorials on languages and technologies such as HTML, JavaScript, and CSS. In addition, our articles cover web frameworks like Angular and React.JS, as well as popular Content Management Systems (CMS) that include WordPress, Drupal, and Joomla. Website development platforms like Shopify, Squarespace, and Wix are also featured. Topics related to solid web design and Internet Marketing also find a home on HTMLGoodies, as we discuss UX/UI Design, Search Engine Optimization (SEO), and web dev best practices.
Advertiser Disclosure: Some of the products that appear on
this site are from companies from which TechnologyAdvice
receives compensation. This compensation may impact how and
where products appear on this site including, for example,
the order in which they appear. TechnologyAdvice does not
include all companies or all types of products available in
the marketplace.