Explain the five selectors of JQuery framework in detail

Posted by zartzar on Wed, 09 Feb 2022 06:33:48 +0100

Absrtact: today, let's share with you the detailed use methods of the five selectors of JQuery.

This article is shared from Huawei cloud community< [JQuery framework] detailed explanation of the five selectors "family bucket"!!! >Original author: grey ape.

Today, let's share with you the detailed use methods of the five selectors of JQuery, so what is a selector? Functionally, it can filter element tags with similar features, which is very useful when we want to centralize or unify elements with similar features,

Basic operation of selector

First, we need to understand the basic operation used by the selector, which can be divided into three steps:

1. Event binding

The use of selectors requires event binding. Generally speaking, we can bind events to a button and trigger the corresponding event response through the click of the button.

2. Entry function

At the same time, in jQuery, such event binding needs to be written in an entry function

The syntax for establishing an entry function in the code segment of < script > < / script >:

$(function(){

});

Note here: define the window of the entry function in js The onload method is different from the $(function) method,

The details are as follows:

window.onload can only be defined once. If it is defined more than once, the latter will overwrite the former

The $(function) method can be defined multiple times, and the latter will not overwrite the former

3. Style control

After we bind the events of the selector, we can control the style of the corresponding element through the selector. The usual expression here is css method, which can modify the corresponding element style through css method.

Let's take a look at an example of basic operation:

<script type="text/javascript">
   $(function () {
      //tag chooser 
      // Change the background color of all elements named < div > to red
      $("#b2").click(function f() {
         $("div").css("backgroundColor","yellow");
      });
   });
</script>

Next, let's talk about the use of five selectors under the jQuery framework through examples.

1, Basic selector

1. Label selector

Label selectors are also called "element selectors",

Syntax: $("html tag name")

Function: get all elements matching the label element name

//tag chooser 
// Change the background color of all elements named < div > to yellow id="b1"
$("#b1").click(function f() {
   $("div").css("backgroundColor","yellow");
});

2. id selector

Syntax: $("#id attribute value")

Function: get the element matching the specified id attribute value

//id selector 
// Change the background color of the element with id one to pink id="b2"
$("#b2").click(function () {
   $("#one").css("backgroundColor","pink");
});

3. Class selector

Syntax: $("property selector of. class")

Function: get the element matching the specified class attribute value

//Class selector 
// Change the background color of all elements with class mini to red id="b3"
$("#b3").click(function () {
   $(".mini").css("backgroundColor","red");
});

4. Union selector

Syntax: $("selector 1, selector 2....")

Gets all elements selected by multiple selectors

//Union selector
// Change the background color of all < span > elements and elements with ID two to blue id="b4"
$("#b4").click(function () {
   $("span,#two").css("backgroundColor","blue");
});

2, Level selector

1. Descendant selector

Syntax: $("a, B")

Function: select all B elements inside A element

//Descendant Selectors 
// Change the background color of all < div > in < body > to red id="b1"
$("#b1").click(function () {
   $("body div").css("backgroundColor","pink");
});

2. Sub selector

Syntax: $("a > b")

Function: select all B child elements inside element A

// Child selectors 
// Change the background color of < body > inner child < div > to red id="b2"
$("#b2").click(function () {
   $("body > div").css("backgroundColor","red");
});

It should be noted here that there seems to be no difference between the two selectors, but we will find that there are differences when using them. The descendant selector will select all B elements inside element A, while the child selector will only select b elements in the next level element of element A, and the range is smaller than that of the descendant selector. See the following examples for details:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Hierarchy selector</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
   <script  src="../js/jquery-3.3.1.min.js"></script>
   <style type="text/css">
         div,span{
             width: 180px;
             height: 180px;
             margin: 20px;
             background: #9999CC;
             border: #000 1px solid;
            float:left;
             font-size: 17px;
             font-family:Roman;
         }
 
         div .mini{
             width: 50px;
             height: 50px;
             background: #CC66FF;
             border: #000 1px solid;
             font-size: 12px;
             font-family:Roman;
         }
 
         div .mini01{
             width: 50px;
             height: 50px;
             background: #CC66FF;
             border: #000 1px solid;
             font-size: 12px;
             font-family:Roman;
         }
 
    </style>
    <script type="text/javascript">

      $(function () {
         //Descendant Selectors 
         // Change the background color of all < div > in < body > to red
         $("#b1").click(function () {
            $("body div").css("backgroundColor","pink");
         });

         // Child selectors 
         // Change the background color of < body > inner child < div > to red
         $("#b2").click(function () {
            $("body > div").css("backgroundColor","red");
         });

      });
   </script>
 
   </head>
 
   <body>
 
       <input type="button" value="preservation"  class="mini" name="ok"  class="mini" />
       <input type="button" value=" change <body> All inside <div> The background color of is red"  id="b1"/>
       <input type="button" value=" change <body> Inner son <div> The background color of is red"  id="b2"/>
       <h1>There is a miracle called persistence</h1>
       <h2>Confidence comes from effort</h2>
 
        <div id="one">
           id by one  
 
       </div>
 
       <div id="two" class="mini" >
             id by two   class yes mini 
             <div  class="mini" >class yes mini</div>
      </div>
 
       <div class="one" >
             class yes one 
             <div  class="mini" >class yes mini</div>
            <div  class="mini" >class yes mini</div>
       </div>
       <div class="one">
           class yes one 
             <div  class="mini01" >class yes mini01</div>
            <div  class="mini" >class yes mini</div>
      </div>
      <span class="spanone">    span
      </span>
 
   </body>
</html>

3, Attribute selector

1. Attribute name selector

Syntax: $("A [attribute name]")

Action: contains the selector for the specified attribute

// The background color of div element with attribute title is red "id="b1 "“
$("#b1").click(function () {
   $("div[title]").css("backgroundColor","pink");
});

2. Attribute selector

Syntax: $("A [attribute name = 'value'])

Function: contains a selector whose specified attribute is equal to the specified value,

// The background color of div element with attribute title value equal to test is red "id="b2“
 $("#b2").click(function () {
    $("div[title='test']").css("backgroundColor","red");
 });

In this selector, we can expand it according to its functions. For example, we can replace: "=" with "! =", which is a selector where the specified attribute name is not equal to the specified value

 // div elements whose attribute Title Value is not equal to test (those without attribute title will also be selected) have a red background color "id="b3“
 $("#b3").click(function () {
    $("div[title!='test']").css("backgroundColor","red");
 });

According to the usage rules of regular expressions:

"=" is replaced by "^ =", which specifies that the property name is a selector starting with the specified value

 // The background color of div element whose attribute title Value starts with te is red "id="b4“
 $("#b4").click(function () {
    $("div[title^='te']").css("backgroundColor","red");
 });

"=" is replaced by "$=" to specify that the property name is a selector ending with the specified value

 // The background color of div element whose attribute title Value ends with est is red "id="b5“
$("#b5").click(function () {
   $("div[title$='est']").css("backgroundColor","red");
});

"=" is replaced by "* =", which is the selector containing the specified value in the specified attribute name

 // The background color of div element with es in attribute title Value is red "id="b6“
 $("#b6").click(function () {
    $("div[title*='es']").css("backgroundColor","red");
 });

3. Composite attribute selector

Syntax: $("A [attribute name = 'value'] []...")

Role: selector containing multiple attribute conditions

// Select the div element with attribute ID, and then select the div element with attribute title Value "es" in the result. The background color is red "id="b7 "“
$("#b7").click(function () {
 $("div[id][title*='es']").css("backgroundColor","red");
});

4, Filter selector

1. First element selector

Syntax: $("A:first")

Function: get the first element of the selected element

// Change the background color of the first div element to red "id="b1“
$("#b1").click(function () {
   $("div:first").css("backgroundColor","red");
});

2. Tail element selector

Syntax: $("A:last")

Function: get the last element of the selected element

// Change the background color of the last div element to red "id="b2“
$("#b2").click(function () {
   $("div:last").css("backgroundColor","red");
});

3. Non element selector

Syntax: $("not(selector)")

Role: elements that do not include the specified content

// Change the background color of all div elements whose class is not one to red "id="b3
$("#b3").click(function () {
   $("div:not(.one)").css("backgroundColor","red");
});

4. Even selector

Syntax: $("A:even")

Function: count from 0 to get the elements with even index in the selected elements

// Change the background color of div element with even index value to red "id="b4“
$("#b4").click(function () {
   $("div:even").css("backgroundColor","red");
});

5. Odd selector

Syntax: $("A:odd")

Function: count from 0 to obtain the elements with odd index in the selected elements

// Change the background color of div elements with odd index value to red "id="b5 "“
$("#b5").click(function () {
   $("div:odd").css("backgroundColor","red");
});

6. Equal to index selector

Syntax: $("A:eq(index)")

Function: get the element with the specified index among the selected elements

// Change the background color of div element with index value equal to 3 to red "id="b7“
$("#b7").click(function () {
   $("div:eq(3)").css("backgroundColor","red");
});

7. Greater than index selector

Syntax: $("A:gt(index)")

Function: get the elements larger than the specified index in the selected elements

// Change the background color of div elements with index value greater than 3 to red "id="b6“
$("#b6").click(function () {
   $("div:gt(3)").css("backgroundColor","red");
});

8. Less than index selector

Syntax: $("A:lt(index)")

Function: get the elements smaller than the specified index in the selected elements

// Change the background color of div element with index value less than 3 to red "id="b8“
$("#b8").click(function () {
   $("div:lt(3)").css("backgroundColor","red");
});

9. Title selector

Syntax: $(": header")

Function: obtain the title (h1~h6) element, which is a fixed writing method

// Change the background color of all title elements to red "id="b9“
$("#b9").click(function () {
   $(":header").css("backgroundColor","red");
});

5, Form filter selector

1. Available element selectors

Syntax: $("A:enabled")

Function: get the available elements in the selected elements

// Use the val() method of jQuery object to change the value "id="b1 "of available < input > elements in the form“
$("#b1").click(function () {
   $("input[type='text']:enabled").val("aaa");
});

2. Unavailable element selector

Syntax: $("A:disabled")

Function: get the unavailable elements in the selected elements

// Use the val() method of jQuery object to change the value "id="b2 "of unavailable < input > elements in the form“
$("#b2").click(function () {
   $("input[type='text']:disabled").val("bbb");
});

3. Select selector

Syntax: $("A:checked")

Function: get elements selected by radio / check box

// Use the length attribute of jQuery object to obtain the number of check boxes "id="b3 "“
$("#b3").click(function () {
   var lengths = $("input[type='checkbox']:checked").length;
   alert(lengths);
});

4. Select the selector (drop-down box)

Syntax: $("A:selected")

Function: get the element selected in the drop-down box

// Use the length attribute of jQuery object to obtain the number of "id="b4 "selected in the drop-down box“
$("#b4").click(function () {
   var selects = $("#job > option:selected").length;
   alert(selects)
});

One thing to note here: the above two selected selectors have different objects. The first selected selector has a radio / check box, while the second selected selector has a drop-down box. At the same time, for the second selector, its function content is the options contained in < option > < / option > in the drop-down box, Therefore, ">" should be used to specify when using. For details, see the following examples:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Form property filter selector</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
   <script  src="../js/jquery-3.3.1.min.js"></script>
   <style type="text/css">

         #job{
            margin: 20px;
         }
         #edu{
            margin-top:-70px;
         }
 
    </style>
    <script type="text/javascript">
      $(function () {

         // Use the length attribute of jQuery object to obtain the number of check boxes "id="b3 "“
         $("#b3").click(function () {
            var lengths = $("input[type='checkbox']:checked").length;
            alert(lengths);
         });

         // Use the length attribute of jQuery object to obtain the number of "id="b4 "selected in the drop-down box“
         $("#b4").click(function () {
            var selects = $("#job > option:selected").length;
            alert(selects)
         });

      });

   </script>
   </head>
 
   <body>
 
       <input type="button" value="preservation"  class="mini" name="ok"  class="mini" />
       <input type="button" value=" utilize jQuery Object length Property to get the number of check boxes selected"  id="b3"/>
       <input type="button" value=" utilize jQuery Object length Property to get the number of items selected in the drop-down box"  id="b4"/>
 
      <br><br>
 
       <br><br>
       <input type="checkbox" name="items" value="cosmetology" >cosmetology
       <input type="checkbox" name="items" value="IT" >IT
       <input type="checkbox" name="items" value="finance" >finance
       <input type="checkbox" name="items" value="Administration" >Administration
 
       <br><br>
 
        <input type="radio" name="sex" value="male" >male
        <input type="radio" name="sex" value="female" >female
 
         <br><br>
 
        <select name="job" id="job" multiple="multiple" size=4>
           <option>programmer</option>
         <option>Intermediate programmer</option>
         <option>Senior programmer</option>
         <option>System Analyst</option>
          </select>
 
          <select name="edu" id="edu">
           <option>undergraduate</option>
         <option>doctor</option>
         <option>master</option>
         <option>junior college</option>
          </select>
 
      <br/>
 
   </body>
 
</html>

Well, I'll share with you about the use of the five selectors in the jQuery framework, and then I'll continue to share jQuery selectors, DOM operations and advanced contents of jQuery with my friends.

 

Click follow to learn about Huawei's new cloud technology for the first time~

Topics: JQuery Programmer filter