JQuery all kinds of selectors for you to clarify this article


JQuery selector

Any operation of the page needs the support of the node. How to quickly and efficiently find the specified node is also a key point in the front-end development. JQuery provides a series of selectors to help developers achieve this goal, so that developers can deal with less complex selection process and performance optimization, and focus more on the writing of business logic.

JQuery almost supports the mainstream CSS1 ~ CSS3 selector writing, we start from the simplest and most commonly used

1. ID selector: an ID used to find, that is, the ID attribute of an element

  $( "#id" )

The ID selector is also a basic selector. JQuery uses the JavaScript function document. Getelementbyid() to process the ID acquisition. The support of native syntax is always very efficient, so in the operation of DOM acquisition, if you can use ID, consider using this selector. It is worth noting that ID is unique, and each ID value can only be used once in a page. If multiple elements are assigned the same ID, only the first DOM element of the ID selection set is matched. But this kind of behavior should not happen; Pages with more than one element using the same ID are invalid

2. Class selector, as the name suggests, obtains nodes by class style class name

  Description: $(". Class")

Compared with ID selectors, class selectors are less efficient, but they have the advantage of multiple choices. For the same jQuery, if the browser supports class selectors, jQuery is implemented by using JavaScript’s native getelementsbyclassname() function. It’s not difficult to find that jQuery is not only simple in selection, but also easy in selection, Moreover, it’s not hard to think that the $(“. Imooc”). CSS () method must have an implicit loop processing inside, so using jQuery to select nodes is not only simple in selection, but also increases a lot of convenient operation of association. Later, we will slowly learn other advantages.3. Element selector: Selects all elements according to the given (HTML) tag name

  Description: $("element")

Search all nodes of the specified element tag name. This is a collection operation. Similarly, the native method getelementsbytagname() function supports the following example code:

    <div class="aaron">
    <div class="aaron">
    <div class="imooc">
        <p>JQuery select</p>
    <div class="imooc">
        <p>JQuery select</p>

    <script type="text/javascript">
    //Processing by native methods
    //Get all the elements with node tag name Div
    //Add a blue border to each Div
    var divs = document.getElementsByTagName('div');
    for (var i = 0; i < divs.length; i++) {
        divs[i].style.border = "3px solid blue";
    <script type="text/javascript">
    //Pass in tag name P directly through jquery
    //Tags can be multiple, so the result is also a collection
    $("p").css("border", "3px solid red");
Copy code

Group 1: PassgetElementsByTagNameMethod to get all the information of the page<div>elementvar divs = document.getElementsByTagName('div'); divsyesdomCollection object, through the loop to each collection of objects<div>Elements give new meaning toboderStyle 2: same effect,$("p")Select all<p>Element, and style directly by CSS method

4. Full selector (* selector)

In CSS, such a style is often written on the first line

{padding: 0; margin: 0;}

wildcardThis means setting the default margin for all elements. In jQuery, we can also passSelector to select the elements in the document page

Description:$( "*" )

Regardless of jQuery, if you want to get all the elements in the document, you can also get them by passing “*” in document. Getelementsbytagname()

It’s not difficult to find that ID, class and tag can all get the corresponding nodes through native methods, but we need to consider a compatibility issue. I’ll mention it here by the way, for example:

  1. IE will implement the annotation node as an element, so calling getElementsByTagName in IE will contain annotation nodes, which is usually not.
  2. The parameters of getelementbyid are case insensitive in IE8 and later versions
  3. In IE7 and later versions, if the name attribute name of form a uses the ID name of another element B, and a precedes B, getelementbyid will select a
  4. IE8 and later, the browser does not support getelementsbyclassname

5. Level selector

All nodes in a document have one or another relationships. We can use the traditional family relationship to describe the relationship between nodes. We can take the document tree as a genealogy, and then there will be the relationship of father, son, brother and grandson between nodes.

The level selector in the selector is used to deal with this kind of relationship: child element, descendant element, brother element and adjacent element

Through a list, compare the differences between the level selectors

JQuery all kinds of selectors for you to clarify this article

If you look closely, there are still many similarities and differences between level selectors

  1. Each level selector has a reference node
  2. The descendant selector contains the contents of the selection of the child selector
  3. Generally, the sibling selector contains the contents selected by neighboring siblings
  4. The elements selected by adjacent sibling selectors and general sibling selectors must be under the same parent element

6. Basic filter selector

Most of the time, we can’t find the elements we want directly through the basic selector and hierarchical selector. Therefore, jQuery provides a series of filter selectors to find the DOM elements we need more quickly. Many of the filter selectors are not CSS specifications, but jQuery’s own selectors for the convenience of developers

The usage of the filter selector is similar to the pseudo element in CSS. The selector starts with a colon ‘:’, and through a list, you can see the description of the basic filter

JQuery all kinds of selectors for you to clarify this article

matters needing attention:

  1. : EQ (),: LT (),: GT (),: even,: odd are used to filter the set elements of their previous matching expressions. Further filtering is based on the previous matching elements. Note that jQuery sets are indexed from 0
  2. GT is a paragraph filter, starting from the next specified index. GT (1) actually starts from 2

7. Content filter selector

Basic filter selectors are all aimed at element DOM nodes. If we want to filter by content, jQuery also provides a set of content filter selectors. Of course, its rules will also be reflected in its contained sub elements or text content

The content filter is described in the following table:

JQuery all kinds of selectors for you to clarify this article

matters needing attention:

  1. : contains and: has both have the meaning of searching, but contains searches for elements containing “specified text” and has searches for elements containing “specified element”
  2. If: the text matched by contains is contained in the child element of the element, it is also considered to be qualified.
  3. : parent and: empty are the opposite, involving the child elements, including text nodes

8. Visibility filter selector

Elements have display state and hidden state. JQuery expands the visibility filter selector: visible and: Hidden according to the state of elements

The description is as follows:

JQuery all kinds of selectors for you to clarify this article

These two selectors are extensions of jQuery, which seems relatively simple, but the element visibility depends on the applicable style

Hidden selectors not only contain elements whose style is display = “None”, but also include hidden forms, visibility, and so on

There are several ways to hide an element:

  1. The value of CSS display is none.
  2. The form element of type = hidden.
  3. Both width and height are explicitly set to 0.
  4. An ancestor element is hidden and will not be displayed on the page
  5. The value of CSS visibility is hidden
  6. CSS opacity refers to 0

Elements are considered visible if they occupy a certain space in the document. The width or height of the visible element is greater than zero. Elements with visibility: hidden or opacity: 0 are considered visible because they still occupy space layout.

9. Property filter selector

Attribute selectors allow you to locate an element based on attributes. You can only specify an attribute of the element, so that all elements that use the attribute regardless of its value will be located. You can also more clearly and locate the elements that use specific values on these attributes. This is where the attribute selector shows their power.

JQuery all kinds of selectors for you to clarify this article

Browser support:

  • [att=val]、[att]、[att|=val]、[att~=val]   It belongs to CSS 2.1 specification
  • [ns|attr], [att ^ = Val], [att * = Val], [att $= Val] belong to CSS3 specification
  • [name!=” value”]   Selectors belonging to jQuery extensions

No matter css2.1 or CSS3, the CSS selector is supported by IE7 and IE8, as well as WebKit, gecko core and opera. Only browsers below IE6 do not support it

Among so many attribute selectors, [attr = “value”] and [attr * = “value”] are the most practical

[attr = “value”] can help us locate different types of elements, especially the operation of form elements. For example, input [type = “text”], input [type = “checkbox”], etc. [attr * = value “] can help us match different types of files in the website

10. Child element filter selector

The child element filter selector is not often used, and its filter rules are slightly more complex than other selectors

Child element filter selector description table:

JQuery all kinds of selectors for you to clarify this article

matters needing attention:

  1. : first only matches a single element, but: first child selector can match multiple: that is, match the first child element for each parent element. This is equivalent to: nth child (1)
  2. The: last only matches a single element, and the: last child selector can match multiple elements: that is, the last child element is matched for each parent element
  3. If there is only one child element,: first child and: last child are the same
  4. : only child matches if an element is the only child element in the parent element, that is to say, the current child element is the only element in the parent element
  5. JQuery implementation: nth child (n) is strictly from CSS specification, so the value of n is “index”, that is, counting from 1, Nth child (index) from 1, and EQ (index) from 0
  6. The difference between nth child (n) and: nth last child (n) is that the former is calculated from front to back and the latter from back to front

11. Form element selector

Whether submitting or transferring data, form elements play a very important role in dynamic interactive pages. The form selector is specially added in jQuery, which makes it extremely convenient to obtain a certain type of form elements

Specific method description of form selector:

JQuery all kinds of selectors for you to clarify this article

matters needing attention:

Except for the input filter selector, almost every form category filter corresponds to the type value of an input element. Most form category filters can be replaced with property filters. For example, (‘: password’) = (‘: password’) = (‘: password’) = (‘: password’) = (‘[type = password]’).

When I first learned CSS, I thought there were too many CSS selectors. At that time, I just wanted to learn basic selectors. When it comes to jQuery, you still need to learn all kinds of selectors. Sure enough, what you owe now will be paid back in the future.

Recommended Today

Sublime text 2 syntax based configuration file

Recently, I was learning python programming language, but I encountered a small problem. The original Ruby coding specification is indented with two spaces, so it was previously set in the global user configuration of sublime”tab_size”: 2Therefore, when editing Python files, you have to set it from the menu every timetab_sizeThe size of the is 4. […]