Attribute Selectors

Target elements by their attributes and attribute values.

Syntax$("[attribute=value]")

Attribute selectors match elements based on their HTML attributes, using square brackets.

SelectorMatches
[type]has a type attribute
[type="text"]type equals text
[href^="https"]href starts with https
[href$=".pdf"]href ends with .pdf
[title*="info"]title contains info

Example

Try it yourself
Loading editor…
Press Run to see the result.

When to use it

  • A form script selects all inputs with a required attribute to add a visual asterisk label.
  • An analytics tool targets all links whose href starts with "https://" to track outbound clicks.
  • A CMS highlights images missing an alt attribute using $("img:not([alt])") during an audit pass.

More examples

Select inputs by type attribute

The [type='text'] attribute selector isolates only text inputs and styles just those.

Example · html
<input type="text" placeholder="Name" />
<input type="email" placeholder="Email" />
<input type="submit" value="Send" />
<script>
$(function () {
  $("input[type='text']").css("border", "2px solid steelblue");
});
</script>

Match href starting with https

The ^= operator matches attributes that start with a value, opening all external links in a new tab.

Example · html
<a href="https://example.com">External</a>
<a href="/about">Internal</a>
<script>
$(function () {
  $("a[href^='https']").attr("target", "_blank");
});
</script>

Flag images lacking alt text

Combining :not() with an attribute selector finds images that lack alt, flagging them for accessibility fixes.

Example · html
<img src="logo.png" alt="Logo" />
<img src="hero.jpg" />
<script>
$(function () {
  $("img:not([alt])").css("outline", "3px solid red");
  console.log("Images missing alt:", $("img:not([alt])").length);
});
</script>

Discussion

  • Be the first to comment on this lesson.