Attribute Value selector
Using the [attribute^=”value”] selector in jQuery, HTML elements can be selected based on a defined string-based attribute value. This and other CSS based selectors in jQuery enable you quickly query and manipulate page components.
Syntax:
This attribute selector has the following general syntax:
$('[attribute^="value"]')
In this syntax:
- Attribute, which can be href, src, id, class, or name, is the name of the HTML attribute you wish to target.
- Value is the string before which the value of the given attribute must begin in order for an element to be chosen.
It is imperative that the value be wrapped in single or double quotation marks.
How it Works
Sizzle is the selection engine that powers jQuery and processes selectors, including attribute selectors like [attribute^=”value”). This engine adds more custom selections to the basic CSS selectors to give users a reliable and effective way to locate components in the Document Object Model (DOM).
This $(selector) section is in charge of “querying” or “finding” HTML elements when you use the $(selector).action() syntax. In particular, [attribute^=”value”]:
Parsing the Selector: The Sizzle engine recognises that [attribute^=”value”] is an attribute selector that searches for values that start with the given string by parsing it.
DOM Traversal: After that, jQuery moves through the DOM tree. It checks each element for the specified attribute.
Value Matching: If the attribute is present in the element, jQuery then contrasts the selection’s value string with the attribute’s real value’s beginning.
Collection Building: A new instance of a jQuery object is created for each element whose attribute value satisfies the “begins with” requirement. Once these matching components are encapsulated in this jQuery object, you may work with them.
The fact that jQuery’s selectors automatically fill in the gaps in the pure DOM concept’s functions and adjust for browser-dependent particularities is a big plus. This ensures consistent and dependable behaviour across officially supported browsers. As a result, you can tackle cross-browser compatibility difficulties when accessing items without writing cumbersome, prone to errors plain JavaScript code.
Code Example
To illustrate [attribute^=”value”], consider a real-world example. The goal is to select all elements with “http://” in their href attribute and start a new tab when clicked.
<!DOCTYPE html>
<html>
<head>
<title>jQuery [src^="..."] Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<style>
img {
width: 100px; height: 75px;
border: 2px solid transparent;
margin: 5px;
}
.highlighted-thumb {
border-color: blue;
box-shadow: 0 0 8px rgba(0, 0, 255, 0.5);
}
</style>
</head>
<body>
<img src="images/full/forest.jpg" alt="Forest">
<img src="images/thumbnails/forest_thumb.jpg" alt="Forest Thumb">
<img src="images/thumbnails/sea_thumb.jpg" alt="Sea Thumb">
<img src="external/photo.jpg" alt="External Photo">
<br><br>
<button id="highlightThumbs">Highlight Thumbnails</button>
<button id="resetImages">Reset</button>
<script>
$(document).ready(function(){
$("#highlightThumbs").click(function(){
$('img[src^="images/thumbnails/"]').addClass("highlighted-thumb");
});
$("#resetImages").click(function(){
$("img").removeClass("highlighted-thumb");
});
});
</script>
</body>
</html>
Output:
Forest Forest Thumb Sea Thumb External Photo
Highlight Thumbnails Reset
Explanation of the Code Example
$(document).ready(function() {…});: This simple jQuery method only performs its logic when the browser loads the page and sets up the Document Object Model (DOM). This prevents jQuery errors with unloaded items.
$(‘a[href^=”http://”]’): All of the page’s HTML elements are targeted by ‘a. [href^=”http://”) The attribute selector is it. Select only <a> elements with “http://” at the start of their href property. In HTML, this is “Secure External Link” and “External Link 1”. Since the href values of the “FTP Document” link (ftp://) and the “Internal Link” link (/internal/) do not start with “http://,” they would not match.
.attr(‘target’, ‘_blank’): When ‘target’ and ‘ blank’ are used, The selector is linked to this jQuery function. For the chosen items, it modifies an attribute in real time. The target attribute of all matched elements is set to blank. Links launch a new browser tab or window.
.addClass(‘external-link’): All matched components receive the CSS class external-link via.addClass(‘external-link’). This enables you to utilise CSS to provide particular styling to these components (for example, an icon next to external links) and improve user experience.
.click(function(event) { … });: This adds a click event handler to your chosen elements. The href of the clicked link will be displayed in an alert box that shows which links the selector was able to successfully target when any of these links are clicked. Although not used specifically in the example, event.preventDefault() is frequently found in click handlers for links and would prevent the browser’s default behaviour of travelling to the link.
Understanding and using [attribute^=”value”] and other jQuery selectors and methods can help you write brief, effective code for more dynamic, interactive, and maintainable online apps.