jQuery Attribute Selector

Using Attribute selector, we can find an element based on their attribute. This allows to specify an element by one of its HTML attributes, such as an image alt attribute or anchor href attribute.

By specifying attribute name in square brackets will return all the elements that have the same attribute irrespective of any values.

Attribute selector syntax with conditions

jQuery attribute selectors perform many conditions, those are listed below -

Selectors Description
$("[attribute]") Select all matched elements with the specified attribute.
$("[attribute='value']") Select all matched elements with the specified attribute and the specified value.
$("[attribute^='value']") Select all matched elements with the specified attribute and start with the specified value.
$("[attribute$='value']") Select all matched elements with the specified attribute and end with the specified value.
$("[attribute*='value']") Select all matched elements with the specified attribute and the value contains specified substring.
$("[attribute!='value']") Select all matched elements that do not contain the specified attribute with the specified value.


Attribute selectors examples

$("[attribute]")

<img src="images/rabbit.jpg" alt="rabbit" style="width: 200px !important;" />
<script>
$(document).ready(function(){
$("[alt]").css("border", " 5px solid black");
});
</script>
rabbit

$("[attribute ='value']")

<img src="images/rabbit.jpg" alt="animal" style="width: 200px !important;" />
<script>
$(document).ready(function(){
$("[alt='animal']").css("border", " 5px solid red");
});
</script>
animal

$("[attribute ^='value']")

<img src="images/rabbit.jpg" alt="pet" style="width: 200px !important;" />
<script>
$(document).ready(function(){
$("[alt ^='pet']").css("border", " 5px solid yellow");
});
</script>
pet

$("[attribute $= 'value']")

<img src="images/rabbit.jpg" alt="mammal" style="width: 200px !important;" />
<script>
$(document).ready(function(){
$("[alt $='mmal']").css("border", " 5px solid green");
});
</script>
mammal

$("[attribute*='value']")

<img src="images/rabbit.jpg" alt="Leporidae" style="width: 200px !important;" />
<script>
$(document).ready(function(){
$("[alt *='epo']").css("border", " 5px solid purple");
});
</script>
Leporidae

$("[attribute!='value']")

<img src="images/rabbit.jpg" alt="domestic" style="width: 200px !important;" />
<script>
$(document).ready(function(){
$("[alt !='wild']").css("border", " 5px solid blue");
});
</script>
domestic


Read more articles


General Knowledge



Learn Popular Language