jQuery Selectors

Selectors play an important role in the jQuery. The use of selectors are to select the HTML element on which, we have to perform some action. So for performing any action or to apply any effects, first we need to select the HTML element.

Syntax of selector

jQuery selector starts with the dollar sign and parenthesis.

$(selector).method();

Example -

$("p"), $("p.demo")

The jQuery selectors select the HTML element based on their name, type , class name, id name and the attribute's value and much more. In the above example, it selects all paragraph elements that has class name 'demo'.



These are the some common selectors used in jQuery

Selectors Description
$(p) All <p> elements are selected.
$(p.classname) All <p> elements with class="classname" are selected.
$(p.idname) All <p> elements with id="idname" are selected.
$("[href]") All elements with href attribute is selected.
$(idname) The element with id="idname" is selected.
$(classname) All elements with class="classname" are selected.

Example of jQuery selectors

<div>
<b>Hello John!</b>
<p>How are you?</p>
</div>

<script>
$(document).ready(function(){
$("div").css("background-color", "yellow");
$("p").css("color", "blue");
$("b").css("color", "red");
});
</script>

Output of the above code

jQuery Name Attribute

In the above example, $("div") selects all the elements of the div tag and set background color to the whole div reason. Similarly, $("p") selects all elements of p tag and set the font color to blue and $("b") selects all the elements of b tag and set the font color to red.

Further, we have explained the most common selectors in brief.





Read more articles


General Knowledge



Learn Popular Language