← Back to Chapters

jQuery Attribute Selectors

? jQuery Attribute Selectors

? Quick Overview

jQuery Attribute Selectors allow you to select HTML elements based on the presence or value of their attributes. They are extremely useful when elements do not have unique IDs or classes but share common attributes.

? Key Concepts

  • Select elements using attribute name
  • Select elements using exact attribute value
  • Select elements using partial matches
  • Useful for forms, links, and dynamic DOM selection

? Syntax / Theory

  • $("[attr]") → selects elements with the attribute
  • $("[attr='value']") → exact match
  • $("[attr!='value']") → not equal
  • $("[attr^='value']") → starts with
  • $("[attr$='value']") → ends with
  • $("[attr*='value']") → contains

? Code Examples

? View Code Example
// Select elements that have a title attribute
$("[title]").css("border","2px solid red");
? View Code Example
// Select input elements with type="text"
$("input[type='text']").css("background","lightyellow");
? View Code Example
// Select links that start with https
$("a[href^='https']").css("color","green");

? Live Output / Explanation

When these selectors run, only the elements matching the attribute condition are affected. This helps target very specific elements without adding extra classes or IDs.

? Interactive Example

Below is a simple interactive idea: clicking the button highlights all elements that contain a specific attribute.

? View Code Example
// Highlight all elements with data-role attribute on button click
$("#btn").click(function(){
$("[data-role]").css("background","#dbeafe");
});

? Use Cases

  • Form validation based on input types
  • Styling external links differently
  • Working with custom data attributes
  • DOM manipulation without modifying HTML structure

✅ Tips & Best Practices

  • Prefer attribute selectors when IDs or classes are unavailable
  • Combine attribute selectors with element selectors for better performance
  • Use data-* attributes for custom logic

? Try It Yourself

  • Select all images with an alt attribute
  • Highlight inputs whose name starts with user
  • Select links that end with .pdf