Page Content

Tutorials

Understanding the Attribute Selector in jQuery With Example

Attribute Selector in jQuery

Regardless of its value, the [attr] selector in jQuery is a potent tool for choosing HTML components based on the existence of a particular attribute. It is among the numerous selectors in jQuery that are derived from CSS selectors, along with some unique ones.

What is the Selector?

The [attr] selection lets you work with HTML elements with a specified attribute. To select all tags with an alt attribute, even if the value changes, this selector is ideal. This selection method is crucial for dynamically modifying a web page’s appearance or content.

Syntax:

$('tagname[attribute]') or $('*[attribute]') or $[attribute].
  • A $: call to a jQuery function indicates jQuery use.
  • (): The selector expression is surrounded by brackets.
  • Optional: You can specify a specific HTML tag name (such as p, div, image, or a) to limit the selection to components of that kind that also possess the attribute.
  • (optional): You can select each element on a page by using the asterisk character. It picks all components with that attribute regardless of tag type when used with [attribute].
  • You search for HTML attributes like src, height, alt, id, rel, and href with the selector [attribute].

To select all elements having a height attribute, use $(‘img[height]’). An omitted tag name, such as $(‘body[onload]’), selects any element with an onload attribute, such as .

How It Works

The [attr] selector is used to discover all Document Object Model (DOM) elements that have the supplied attribute name. Sizzle, jQuery’s selector engine, processes the expression. It merely checks for the attribute’s presence, not its value.

Querying the DOM: In order to “query (or find)” HTML components inside the DOM tree, jQuery makes use of this selector.

Attribute Presence Check: It looks through elements and adds those that possess the specified attribute.

Efficiency: By firmly compensating for browser-dependent particularities and augmenting missing pure DOM methods, this approach streamlines element access.

Unlike other attribute selectors, [attr] just checks for presence:

  • [attr=”value”]: Chooses items with the attr attribute precisely equal to value.
  • Selecting elements with an attr attribute that is not value is done with [attr!=”value”].
  • The function [attr^=”value”] chooses components whose attr attribute starts with value.
  • [attr$=”value”]: Chooses elements whose attr attribute has a value at the end.

Elements whose attr property contains the substring value are chosen using the [attr*=”value”] function.
When the selection criterion is the attribute’s very presence rather than its particular value or pattern, the [attr] selector is a more versatile attribute selector that can be helpful.

Code Example

A useful example that selects all elements with a title property and then shows their title content will help us better understand the [attr] selector.

<!DOCTYPE html>
<html>
<head>
  <title>jQuery [attr] Selector</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <style>
    .highlight {
      background-color: yellow;
      padding: 5px;
    }
  </style>
</head>
<body>
  <h3>Click the Button to Highlight Elements with "title"</h3>
  <p title="Hello from paragraph">Paragraph with title</p>
  <span title="This is a span">Span with title</span>
  <p>No title here</p>
  <button id="highlightBtn">Highlight</button>
  <div id="result"></div>
  <script>
    $(document).ready(function() {
      $('#highlightBtn').click(function() {
        let msg = '';
        $('[title]').each(function() {
          $(this).addClass('highlight');
          msg += `<p>Found &lt;${this.tagName.toLowerCase()}&gt; with title: <b>${$(this).attr("title")}</b></p>`;
        });
        $('#result').html(msg);
      });
    });
  </script>
</body>
</html>

Output:

Click the Button to Highlight Elements with "title"
Paragraph with title
Span with title
No title here
Highlight
Found <p> with title: Hello from paragraph
Found <span> with title: This is a span

How the Code Example Works

jQuery Inclusion: The sample starts with a Content Delivery Network (CDN) connection to the jQuery library. As a result, the browser can reliably and swiftly download the library.

$(document).ready(): This makes sure that the jQuery code inside it only executes when the DOM (content Object Model) has been properly created and the entire HTML content has loaded. This stops problems from happening if JavaScript tries to access elements that aren’t on the page yet.

Button Click Event: The button has an event handler attached to it with the id=”selectButton” property. Clicking this button initiates the execution of the code defined in.click().

$(‘[title]’) Selector: $(‘[title]’) is used inside the click handler. The demonstration’s fundamental idea is this. It instructs jQuery to locate and pick any HTML element on the page that has the title attribute, regardless of the value that the attribute may contain.

.each(function(index) { … }): Next, the chosen collection of elements is subjected to the.each() method. By iterating through each element in the matched set, you may take action on each one separately.

  • $(this): The current DOM element being handled in the loop is referenced inside the.each() function. ccc
  • The tagName property of DOM elements like “P”, “SPAN”, “A”, and “IMG” is obtained using.prop(‘tagName’).
  • .attr(‘title’): The value of the title attribute for the current element is obtained using this method. Generally speaking, attr() is used to modify attributes as they appear in the HTML . For many attributes,.attr() is frequently used as place of.prop(); nevertheless, it specifically handles the HTML attribute.
  • .addClass(‘highlight’): This function dynamically gives the chosen element the CSS class highlight. This modifies the visual style of the element on the page without requiring a page reload.

$(‘#output’).html(titlesFound): The titlesFound string, which compiles details about every element that is found, is then added to the div element with id=”output” using the.html() method.

In order to facilitate further manipulation or information extraction from elements, this example shows how the [attr] selector effectively chooses all elements that possess a particular attribute. Rich interactive web front ends can be built with this technology.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index