jQuery selector 

The core component of jQuery is the selector engine, which inherits the css syntax and can quickly and accurately select the tag name, attribute name, state, etc. of the DOM element, without worrying about browser compatibility.

So the jQuery selectors we've introduced below are mostly similar to the CSS selectors we've studied before.

The CSS selector is used to find and position the elements in the page and set the style to the element.

The jQuery selector is also used to find elements. After we find the elements, we can use some given methods to modify, delete, and even move the elements.

When using the jQuery selector, we must use the "$()" function to wrap our css rules, and the css rules are passed as parameters to the inside of the jQuery object, returning the jQuery object containing the corresponding elements in the page, then we It is possible to perform behavioral operations on this acquired DOM node.

Element selector


The jQuery element selector picks an element based on the element name.

Select all <p> elements in the page:

$("p")

Instance

When the user clicks the button, all <p> will change color:

 
Run the program and try it out

#id selector


The jQuery #id selector picks the specified element by the id attribute of the HTML element.

Note: IDs are only allowed to appear once on the page. We generally require developers to adhere to and maintain this rule. But if you appear three times in the page and use the css style, then these three elements will also perform, but if you do this in jQuery, you will run into problems, only one ID will take effect, so we must Get into the habit of using only one ID on the page

The syntax for selecting elements by id is as follows:

$("#test")

Instance

When the user clicks the button, the element with the id="test" attribute turns red:

 
Run the program and try it out

.class selector


The jQuery class selector can find elements by the specified class.

The syntax is as follows:

$(".test")

Instance

When the user clicks the button, all elements with the class="test" attribute will change color:

Run the program and try it out


More selector examples

GrammarDescription
$(this)Current HTML element
$("p")All <p> elements
$("p.intro")All <p> elements of class="intro"
$(".intro")All elements of class="intro"
$("#intro")Element of id="intro"
$("ul li:first")The first <li> element of each <ul>
$("[href$='.jpg']")All href attributes with attribute values ​​ending in ".jpg"
$("div#intro .head")All elements of class="head" in the <div> element of id="intro"




Last Updated: 2018-11-24 13:31:38 By Akshay

SHARE THIS

share_facebook share_twitter share_google_plus

Please Comment Here :