Attribute Selectors
In this page:
Has an Attribute
Wrapping an attribute name in square brackets selects every element that has that attribute set, no matter its value. It's useful when you only care whether an attribute is present at all.
Example: Has an Attribute
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<input title="tip"><input>
<script>
console.log($("[title]").length);
</script>
</body>
</html>
Attribute Equals
Adding an equals sign and a value inside the brackets, like [type="text"], narrows the match down to elements where that attribute equals exactly that value. This is a strict, case-sensitive equality check, so it won't match a value that's merely similar.
Example: Attribute Equals
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<input type="text"><input type="checkbox">
<script>
console.log($("[type='text']").length);
</script>
</body>
</html>
Attribute Starts With
A caret before the equals sign, like [href^="https"], matches elements whose attribute value starts with the given text -- handy for finding all external links on a page. This pattern is a fast way to select every link pointing to an external HTTPS site without checking each href manually.
Example: Attribute Starts With
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<a href="https://example.com">Ext</a>
<a href="/local">Local</a>
<script>
console.log($("[href^='https']").length);
</script>
</body>
</html>
Attribute Ends With
A dollar sign before the equals sign, like [src$=".png"], matches elements whose attribute value ends with the given text, useful for filtering by file extension. This is a common way to select all images of a specific format, like every PNG icon on a page, in one line.
Example: Attribute Ends With
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<img src="icon.png"><img src="photo.jpg">
<script>
console.log($("[src$='.png']").length);
</script>
</body>
</html>
Attribute Contains
An asterisk before the equals sign, like [alt*="logo"], matches elements whose attribute value contains the given text anywhere inside it, the most permissive of the attribute-value matchers.
Example: Attribute Contains
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<img alt="company logo"><img alt="banner">
<script>
console.log($("[alt*='logo']").length);
</script>
</body>
</html>
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: