You can use the attribute selector to select an element by one of its HTML attributes, such as a link’s target attribute or an input’s type attribute, etc.
For example, the following jQuery code will select and highlight all the text inputs i.e. <input> elements with the type="text", when the document is ready.
Example
<script>
$(document).ready(function(){
// Highlight paragraph elements
$('input[type="text"]').css("background", "yellow");
});
</script>
Selecting Elements by Compound CSS Selector
You can also combine the CSS selectors to make your selection even more precise.
For instance, you can combine the class selector with an element selector to find the elements in a document that has certain type and class.
Example
<script>
$(document).ready(function(){
// Highlight only paragraph elements with class mark
$("p.mark").css("background", "yellow");
// Highlight only span elements inside the element with ID mark
$("#mark span").css("background", "yellow");
// Highlight li elements inside the ul elements
$("ul li").css("background", "red");
// Highlight li elements only inside the ul element with id mark
$("ul#mark li").css("background", "yellow");
// Highlight li elements inside all the ul element with class mark
$("ul.mark li").css("background", "green");
// Highlight all anchor elements with target blank
$('a[target="_blank"]').css("background", "yellow");
});
</script>
jQuery Custom Selector
In addition to the CSS defined selectors, jQuery provides its own custom selector to further enhancing the capabilities of selecting elements on a page.
Example
<script>
$(document).ready(function(){
// Highlight table rows appearing at odd places
$("tr:odd").css("background", "yellow");
// Highlight table rows appearing at even places
$("tr:even").css("background", "orange");
// Highlight first paragraph element
$("p:first").css("background", "red");
// Highlight last paragraph element
$("p:last").css("background", "green");
// Highlight all input elements with type text inside a form
$("form :text").css("background", "purple");
// Highlight all input elements with type password inside a form
$("form :password").css("background", "blue");
// Highlight all input elements with type submit inside a form
$("form :submit").css("background", "violet");
});
</script>