Home >Web Front-end >JS Tutorial >An introduction to jquery's commonly used selector types and their usage principles

An introduction to jquery's commonly used selector types and their usage principles

伊谢尔伦
伊谢尔伦Original
2017-06-16 10:23:311682browse

jquery selector, css3 selector, various selectors, as a very flexible jquery selector, how to use it?

1. Basic usage of jQuery selector

In CSS3 selector standard jQuery supports a fairly complete subset of the selector syntax defined in the draft, and also adds some non-standard but useful pseudo-classes. Note: This section is about jQuery selectors. Many of these selectors (but not all) can be used in CSS style sheets. Selector syntax has a three-level structure. You've no doubt seen selectors in their simplest form. "#te st" selects the element with the id attribute "test". "blockquote" selects all

elements in the document, while "p.note" selects all
elements with the class attribute "note". Simple selectors can be combined into "combined selectors", such as "p.note>p" and "blockquote i", as long as the combining characters are used as separators. Simple and combined selectors can also be grouped into comma-separated lists. This type of selector group is the most common form of selection passed to the $() function. Before explaining combined selectors and selector groups, we must first understand the syntax of simple selectors.

An introduction to jquerys commonly used selector types and their usage principles

##1. Use simple selector

The beginning of a simple selector (either explicitly or implicitly) is the tag type declaration. For example, if you are only interested in

elements, a simple selector can start with "P". If the selected element has nothing to do with the tag name, you can use the wildcard "*" instead. If the selector does not begin with a tag name or a wildcard, a wildcard is implicitly included.

The tag name or wildcard specifies an initial set of alternative document elements. In a simple selector, the part after the tag type declaration consists of zero or more filters. Filters are applied from left to right, in the order they are written, and each of them narrows the set of selected elements. The following table lists the filters supported by jQuery.

jQuery selection filter

Filter Meaning

# id Matches elements whose id attribute is id. In a valid ITML document, there will never be multiple elements with the same ID, so this filter is usually used as a standalone selector

.class Match the class attribute (which is a string of words that are parsed into a list of words separated by spaces) containing all elements with the class word

[attr] Matches the attr attribute ( (regardless of value)

[attr=val] Matches all elements that have the attr attribute and the value is val

[attr!=val] Matches all elements that do not have an attr attribute, or the value of the attr attribute is not val ((jQuery extension)

[ attr^=val] Match elements whose attr attribute value starts with val

[attr$=val] Match elements whose attr attribute value starts with val The ending element

[attr*=val] matches the element whose attr attribute value contains val

[attr~ =val] Matches elements containing the word val when their attr attribute is interpreted as a space-separated list of words, so the selector "p.note" is the same as "p [class~=note]". Same

[attr|=val] Matches elements whose attr attribute value starts with val and is not followed by other characters, or other characters start with a hyphen

:animated Matches the element being animated, which is generated by jQuery

:button Match

:checkbox Matches elements (an extension of jQuery). This filter is more efficient when explicitly prefixed with the input tag "input:checkbox"

:checked Match the selected input element

:contains(text) Match contains Specifies the text element (jQuery extension). The parentheses in this filter scope the text—no quotes are required. The text of the filtered element is determined by the textContent or innerText attribute - this is the original document text, without tags and comments

:disabled matches disabled Element

:empty Matches elements that have no child nodes and no text content

:enabled Match elements that are not disabled

:eq(n) Matches the nth element in the selected list based on document order and serial number starting from 0 (jQuery Extension)

:even Matches even-numbered elements in the list. Since the sequence number of the first element is 0, the first, third, fifth, etc. elements are actually selected (jQuery extension)

:file Match elements (jQuery extension)

:first Match the first element in the list. Same as ":eq(0)" (jQuery extension)

:first-child The matched element is the first child element of its parent node. Note: This is different from ":first"

:gt(n) Matches elements with a sequence number greater than n in a selected list based on document order and starting from 0 (jQuery extension)

:has(sel) The matched element has descendant elements that match the embedded selector sel

:header Matches all header elements:

,

,

,

,

or
(jQuery extension)

:hidden Matches all elements that are not visible on the screen: Generally speaking, it can be considered that the offsetWidth and offsetHeight of these elements are 0

:image Match elements. Note that this filter will not match An introduction to jquery's commonly used selector types and their usage principles elements (jQuery extension)

:input Matches user input elements: ,

:last matches the last element in the selected list((jQuery extension)

##:last-child The matched element is the last child element of its parent node. Note: This is different from ":last".

:lt(n) Matches elements with serial numbers less than n in the selected list based on document order and starting from 0 (jQuery extension)

:not(sel) The matched element does not match the inline selector sel

:nth(n) Same as ":eq(n)" (extension of jQuery)

:nth-child(n) The matched element is the nth child of its parent node element. . It can be a numerical value, the word even, the word odd or a calculation formula. Use ":nth-child(even)" to select elements that are ranked 2nd or 4th among the child elements of their parent node. Use ":nth-child(odd)" to select elements that are ranked 1st, 3rd, etc. among the child elements of their parent node.

The more common situation is that n is a calculation formula such as xn or x n+y, where x and y are integers and n is a literal n. Therefore, you can use nth-child(3n+1) to select the 1st, 4th, 7th, etc. elements.

Note that the sequence number of this filter starts from 1, so if an element is the first child element of its parent node, it will be considered an odd element and the match will be 3n +1 instead of 3n. To distinguish it from the ":even" and ":odd" filters, the matching sequence number of the latter starts from 0.

:odd in the matching list Elements with odd numbers (starting from 0). Note that elements with numbers 1 and 3 are the 2nd and 4th matching elements respectively (jQuery extension)

##:only-child Matches elements that are the only child nodes of its parent node

:parent Matches elements that are parent nodes, which is the same as ":empty" On the contrary (jQuery extension)

:password Match element (jQuery extension)

:radio Match elements (extension of j Query)

:reset Match and

:selected match The selected

##:submit

match and

:text

matchesElement (jQuery extension)

:visible

Matches all currently visible elements: Generally speaking, the offsetWidth and The value of offsetHeight is not 0, which is the opposite of ":hidden"

Note: Some selectors listed in the table accept parameters in parentheses. For example, the following selector selects. Elements ranked 1st or 2nd among the child elements of their parent node, as long as they contain the word "JavaScript", do not include elements

p:nth-child(3n+. 1): text (JavaScript):not(:has(a))

Generally speaking, specifying the tag type prefix can make the filter run more efficiently. For example, don't be simple. Use ":radio" to select radio buttons, "input:radio" would be better. The exception is the ID filter, which is more efficient without adding a tag prefix. For example, the selector "#address" is often more efficient than the more explicit "form#address".

2. Usage of combination selector

Use special operators or "combinator" ” Simple selectors can be combined to express relationships between elements in the document tree. The following table lists the combined selectors supported by jQuery. These combination selectors are the same as those supported by CSS3.

Here are some examples of combined selectors:

"Blockquote I" // matching & lt; blockquote & gt; in the & lt; i & gt & gt

"OL & GT; li" // & lt; 1i & gt; & lt; of & gt; direct sub -element

"#OUTPUT+*" // ID = "Output". p.note > h1+p" //Follow the

element of

, inside

Pay attention to the combination Selectors are not limited to combining two selectors: combining three or more selectors is also allowed. Combination selectors are processed from left to right.

3. Selector combination

is passed to the $() function (or in The selector used in a style sheet is a selector group, which is a comma-separated list of one or more simple selectors or combined selectors. Elements matched by a selector group only need to match any selector in the selector group. For us, a simple selector can also be thought of as a selector group. Here are some examples of the choice device group:

# "H1, H2, H3" // matching & lt; h1 & gt;, & lt; h2 & gt; and & lt; h3 & gt; element

#"#p1, #p2, #p3" //Match elements with IDs of p1, p2 or p3

"p.note, p.note " //Match

and

elements of class="note"

##"body>p,p.note>p" //

and

child elements of

Note: CSS and jQuery selector syntax allow the use of circles in certain filters of simple selectors parentheses, but does not allow the use of parentheses for more common groupings. For example, you cannot put selector groups or combinations of selectors in parentheses and treat them as simple selectors:

(h1, h2, h3)+p //Illegal

h1+p, h2+p, h3+p //Correct way to write


##2. How to select

In addition to the selector syntax supported by the $() function, jQuery also defines some selection methods. Most of the jQuery methods we've seen in this chapter perform some kind of operation on the selected element. Selection methods are different: they modify the set of selected elements, extract, expand or simply serve as a starting point for new selection operations.

This section describes these selection methods. You'll notice that most of these selection methods provide the same functionality as the selector syntax.

The easiest way to extract selected elements is to extract them by position. The jQuery object returned by first() only contains the first selected element, and the jQuery object returned by last() only contains the last element. More generally, the Query object returned by the eq() method contains only a single selected element with the specified sequence number. (In jQuery 1.4, negative numbers are also allowed, counting from the end of the selection.) Note that the jQuery object returned by these methods contains only one element. This is different from the common array serial number. The single element returned by the array serial number is not packaged by jQuery:

var paras=$("p");

Paras.first () // Only select the first & lt; p & gt; element

# Parast () // Only select the last & lt; p & gt;

paras.eq(1)                                                                                                                                                 use   using           using ’ ’s ’ using ’s ’ s The second to last

##paras[1]                                                                                                                                                                                                  but                          

The more general method of extracting a selection by position is slice()o jQuery's slice() method is similar to the Array.slice() method: the former accepts the starting and ending serial numbers (negative serial numbers will be calculated from the end), The returned jQuery object contains the set of elements from the start to the end sequence number (but not including the end sequence number). If the end sequence number is omitted, the returned object will contain all elements from the start sequence number:

$("p").slice(2,5) //Select the 3rd, The 4th and 5th

elements

$("p").slice(-3) //Select the last 3

elements

filter() is a general selection filtering method. There are 3 calling methods:

Pass the selector string to filter() and it will return A jQuery object containing only selected elements that also match this selector.

Pass another jQuery object to filter(), which will return a new jQuery object that contains the intersection of the two Query objects. You can also pass an array of elements or even a single document element to filter().

Pass the judgment function to filter(), and the function will be called for each matching element. filter() returns a jQuery object containing only the judgment function that is true (or any true value )Elements. When calling the judgment function, the this value is the current element, and the parameter is the element number.

$("p").filter(".note") //Same as $("p.note")

$("p").filter($(".note")) //Same as $("p.note")

$("p") .filter(function(idx){return idx%2 == 0}) //Same as $("p:even")

not() method is the same as filter() , except that the meaning is opposite to filter(). If you pass a selector string to not() it will return a new jQuery object containing only elements that do not match the selector. If you pass a jQuery object, an array of elements, or a single element to not(), it will return all selected elements except those explicitly excluded. If you pass a judgment function to not(), the judgment function is called just like in filter(), except that the returned jQuery object contains only those elements that cause the judgment function to return false or other false values:

$("p").not("#header, #footer"); //All elements except two special elements

In jQuery 1.4 , another way to extract a selection is the has() method. If a selector is passed in, has() will return a new jQuery object containing only selected elements whose descendants match the selector. If you pass a document element to has(), it will adjust the set of selected elements to those selected elements that are ancestor nodes of the specified element:

##$("p").has(" a[href]") //Paragraph containing links

add() method will expand the selection instead of filtering or extracting it. Any parameters (except functions) passed to the $() function can also be passed to the add() method. The add() method returns the original selected elements, plus those elements selected (or created) by the parameters passed to the $() function. add() will remove duplicate elements and sort the combined selection so that the elements are in the order in the document:

//Select all

and all

Equivalent way of elements

$("p, p") //Use selector group

$("p").add(p) //Pass selector to add()

$("p").add($("p")) / /Pass in the jQuery object to add()

var paras = document.getElementsByTagName("p"); //Array-like object

$("p").add(paras); //Pass in the element array to add()

1. Restore to the previous selected element set

In order to realize the chain call of methods, many jQuery object methods will eventually return the calling object. However, the methods described in this section all return new jQuery objects. You can continue to call in a chain, but you must clearly realize that the element set operated after the chain call may no longer be the element set at the beginning of the chain call.

The actual situation is more complicated. When the selection methods described here create or return a new ejQuery object, they add an internal reference to the old jQuery object from which it was derived. This creates a linked list or stack of jQuery objects. The end() method is used to pop the stack and return the saved jQuery object. Calling end() in a chain of calls will restore the set of matching elements to its previous state. Consider the following code:

//Find all

elements, then look for

elements

//High Highlight the

element, and then add a border to the

element

//First, do not use chained calls

var ps = $("p");

var paras = p.find("p");

paras.addClass ("highlight");

ps.css("border", "solid black 1px");

# #//The following shows how to use chain calls to achieve

$("p").find("p").addClass("highlight").end().css ("border", "solid black 1px");

//You can also reverse the order of operations to avoid calling end()

$("p").css("border", "solid block 1px").find("p").addClass("highlight");

If you want to define it manually To select a set of elements while maintaining compatibility with the end() method, you can pass the new set of elements to the push5tack() method as an array or array-like object. The specified element will become the new selected element, and the previously selected element set will be pushed onto the stack. They can then be restored using the end() method:

var sel = $(" p");                         //Select all

elements

sel.pushStack(document.getElementsByTagName("p"));       //Change to all

elements

sel.end (); There is one last method that needs to be explained in the selection stack. andSelf() returns a new jQuery object containing all currently selected elements, plus all previously selected elements (duplicates will be removed). andSelf() is the same as the add() method, perhaps "addPrev" is a more descriptive name. As an example, consider the following variation of the above code: highlighting the

element and the

elements in its parent node, and then adding a border to those

elements:

$("p").find("p").andSelf().                     //Find

in

addClass("highlight").                                                                                                                 use   with using                                 ‐                          to be highlighted. ##css("border", "solid black 1px"); //Add a border to ps

2. Select the element The set is used as a context

The filter(), add(), and not() methods described above will perform intersection, and Set and difference operations. jQuery also defines some other selection methods that can use the currently selected set of elements as context. For each selected element, these methods will use the selected element as a context or starting point to get a new set of selected elements, and then return a new jQuery object containing the union of all new selected elements. Similar to the add() method, duplicate elements are removed and sorted so that the elements are arranged in the order they appear in the document.

The most common selection method in this category is find(). It searches for elements that match the specified selector string among the descendants of each currently selected element, and then it returns a new jQuery object representing the set of matched descendants. Note that these newly selected elements will not be merged into the existing set of selected elements. Also note that find() is different from filter(). filter() will not select new elements, but simply reduce the currently selected element set:

$("p").find("p") //Find elements in, same as $("p p")

in this category Other methods return new jQuery objects that represent the child elements, siblings, or parent elements of each element in the currently selected element set. Most accept an optional selector string as argument. When no selector is passed in, they return all child elements, siblings, or parent elements. When selectors are passed in, they filter the set of elements, returning only those that match.

The children() method returns the direct child elements of each selected element, which can be filtered with optional selector parameters:

/ /Find all elements in the child node elements with IDs of "header" and "footer" elements

//With $("#header>span, #footer> span") is the same as

$("#header, #footer").children("span")

contents() method is the same as The children() method is similar, except that it returns all child nodes of each element, including text nodes. If there is an

next() and prev() methods return the next and previous sibling elements (if any) of each selected element. If a selector is passed in, only sibling elements matching the selector will be selected:

$("h1").next("p") //With $("h1 +p") the same

$("h1").prev() //The sibling element in front of the

element

nextAll() and prevAll() return all sibling elements before or after each selected element (if any). The siblings() method returns all sibling elements of each selected element (the selected element itself is not its own sibling element). If you pass a selector to these methods, only matching sibling elements will be returned:

$("#footer").nextAll("p") //Follow the #footer element All

sibling elements

$("#footer").prevAll() //All sibling elements in front of the #footer element

Starting from jQuery 1.4, the nextUntil() and prevUntil() methods accept a selector parameter and will select all sibling elements after or in front of the selected element until a sibling element matching the selector is found. If the selector is omitted, these two methods behave the same as nextAll() and prevAll() without a selector.

parent() method returns the parent node of each selected element:

##$("li").parent() //List The parent nodes of elements, such as and

    elements

##parents() method returns the ancestor nodes of each selected element (up to the element). Both parent() and parents() accept an optional selector string parameter:

$("a[href]").parents("p") //Contains Linked

elements

##parentsUntil() returns the ancestor elements of each selected element until the first ancestor element matching the specified selector appears. The closest() method must pass a selector string, and will return the nearest ancestor element matching the selector among the ancestor elements of each selected element (if any). For this method, elements are considered to be their own ancestors. In jQuery 1.4, you can also pass an ancestor element as the second parameter to closest() to prevent jQuery from going beyond the specified element when searching upward:

$(" a[href]").closest("p") //The innermost layer containing the link

$("a[href]").parentsUntil(" :not(p)") //All the

elements that wrap

The above is the complete introduction to the jquery selector and its principles. Thank you for reading!


The above is the detailed content of An introduction to jquery's commonly used selector types and their usage principles. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn