In this tutorial we will see how to Select All HTML Elements Whose ID Start With Same String using JavaScript. The querySelectorAll and substring matching attribute selector are used for this.
Table of Contents
HTML Code
HTML Code is given below, This code contains three different HTML elements. One H1 heading, One Paragraph element and One Span Tag. All these tags have different ids. But id of two tags start with same term (HTCS). When button is clicked the JavaScript code will only select two elements whose id start with same string.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Select All HTML Elements Whose ID Start With Same String</title>
</head>
<body>
<p>Select All Elements With ID that starts with "HTCS".</p>
<h1 id='HTCS031121312'>Heading</h1>
<p id='HTSC4823425'>Paragraph</p>
<span id='HTCS9083405'>Span Tag</span>
<button onclick="selectElems()">Get Elements</button>
</body>
</html>
querySelectorAll() Method
The querySelectorAll() Method is used to select or target all HTML elements that matches with specified CSS Selector.
The querySelectorAll() Method will return a list of all HTML elements which match the specified group of selectors.
In this example we have used Substring Matching Attribute Selector inside querySelectorAll() Method.
Substring Matching Attribute Selector
There are three Substring Matching Attribute Selectors. We have used [attribute^="value"] in this example, which match the defined value with the prefix of value of id attribute.
In this example, the value of id attribute is matched with the defined string and the matched elements are selected whose id start with that defined string.
It is also known as Attribute Starts With Selector.
JavaScript Code
In this example, main function selectElems() will be executed on button click. Then querySelectorAll() Method will only select those elements whose id start with the term 'HTCS'.
querySelectorAll() Method does this with the help of [attribute^="value"] selector. The for loop is then used to change background color of all selected elements one by one.
Take a look at the code given below.
<script>
function selectElems()
{
var tags = document.querySelectorAll('*[id^="HTCS"]');
for (var i = 0; i < tags.length; i++) {
tags.item(i).style.backgroundColor = "red";
}
}
</script>
Demo
Video Tutorial
Watch video tutorial on how to Select All HTML Elements Whose ID Start With Same String using JavaScript.