In this tutorial we will see how to Select All HTML Elements Whose ID Start With Same String with jQuery. The Attribute Starts With Selector and jQuery css() method 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 jQuery code will only select two elements whose id start with same string.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Select All HTML Elements Whose ID Start With Same String</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</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>Get Elements</button>
</body>
</html>
Attribute Starts With Selector
The Attribute Starts With Selector is a type of Substring Matching Attribute Selectors. This selector selects all elements whose value of specific attribute starts with the defined string.
In this example it will select all elements whose id attribute value starts with defined string (HTCS).
jQuery css() method
The jQuery css() method sets or returns the CSS properties of the selected HTML element.
In this example jQuery css() method will change the background color of the selected elements.
JQuery Code
JQuery Code is given below, The code will only be executed once the button is clicked. This is done using jQuery click() method.
Then on function execution the Attribute Starts With Selector ([attribute^=”value”]) will select only those elements whose id start with defined string.
The background color of these elements are changed using jQuery css() method.
Take a look at the code given below.
<script>
$("button").click(function(){
var elems = $('[id^="HTCS"]').css("background-color", "red");
});
</script>
Demo
Video Tutorial
Watch video tutorial on how to Select All HTML Elements Whose ID Start With Same String with jQuery.