Using attributes
In the previous chapter, we saw how we could find elements in a page from their class or their ID. These two properties are related because of the fact that you can use them to style the elements with CSS, but with jQuery, you can actually find elements based on any kind of attribute. It comes with a bunch of attribute selector types and in this article, we will look into some of them.
Find elements with a specific attribute
The most basic task when selecting elements based on attributes is to find all the elements which has a specific attribute. Be aware that the next example doesn't require the attribute to have a specific value, in fact, it doesn't even require it to have a value. The syntax for this selector is a set of square brackets with the name of the desired attribute inside it, for instance [name] or [href]. Here is an example:
<span title="Title 1">Test 1</span><br />
<span>Test 2</span><br />
<span title="Title 3">Test 3</span><br />
<script type="text/javascript">
$(function()
{
$("[title]").css("text-decoration", "underline");
});
</script>
We use the attribute selector to find all elements on the page which has a title attribute and then underline it. As mentioned, this will match elements with a title element no matter what their value is, but sometimes you will want to find elements with a specific attribute which has a specific value.
Find elements with a specific value for a specific attribute
Here's an example where we find elements with a specific value:
<a href="http://www.google.com" target="_blank">Link 1</a><br />
<a href="http://www.google.com" target="_self">Link 2</a><br />
<a href="http://www.google.com" target="_blank">Link 3</a><br />
<script type="text/javascript">
$(function()
{
$("a[target='_blank']").append(" [new window]");
});
</script>
The selector simply tells jQuery to find all links (the a elements) which has a target attribute that equals the string value "_blank" and then append the text "[new window]" to them. But what if you're looking for all elements which don't have the value? Inverting the selector is very easy:
$("a[target!='_blank']").append(" [same window]");
The difference is the != instead of =, a common way of negating an operator within many programming languages.
And there's even more possibilities:
Find elements with a value which starts with a specific string using the ^= operator:
$("input[name^='txt']").css("color", "blue");
Find elements with a value which ends with a specific string using the $= operator:
$("input[name$='letter']").css("color", "red");
Find elements with a value which contains a specific word:
$("input[name*='txt']").css("color", "blue");