This article introduces the usage of JQuery selector. For more information, see
The jQuery element selector and attribute selector allow you to select HTML elements by Tag Name, attribute name, or content.
JQuery element selector:JQuery uses the CSS selector to select HTML elements.
$ ("P") Select
Element.
$ ("P. intro") select all class = "intro"
Element.
$ ("P # demo") Select the first id = "demo"
Element.
JQuery attribute selector:JQuery uses an XPath expression to select an element with a given attribute.
$ ("[Href]") selects all elements with the href attribute.
$ ("[Href = '#']") select all elements with an href value equal.
$ ("[Href! = '#'] ") Select all elements with an href value not equal.
$ ("Your href00000000'.jpg ']") select all elements whose href values end with ". jpg.
Selector instance
Syntax |
Description |
$ (This) |
Current HTML Element |
$ ("P ") |
All Element |
$ ("P. intro ") |
All class = "intro" Element |
$ (". Intro ") |
All class = "intro" Elements |
$ ("# Intro ") |
Id = the first element of "intro" |
$ ("Ul li: first ") |
Each
|
$ ("Your href00000000'.jpg ']") |
All href attributes with attribute values ending with ". jpg" |
$ ("P # intro. head ") |
Id = "intro" All class = "head" elements in the element |
GET/set content-text (), html (), and val ()
We will use three identical methods in the previous chapter to set the content:
- Text ()-set or return the text content of the selected Element
- Html ()-set or return the content of the selected element (including HTML tags)
- Val ()-set or return the value of a form field
- Attr ()-sets the property value of the selected element to be returned.
The preceding four jQuery methods include text (), html (), val (), and attr (), which also have callback functions. The callback function has two parameters: the subscript of the current element in the list of selected elements and the original (old) value. Then return the string you want to use with the new value of the function.
$("#btn1").click(function(){ $("#test1").text(function(i,origText){ return "Old text: " + origText + " New text: Hello world ! (index: " + i + ")"; //return newText; });});