jquery selector(2)

1. Introduction to jQuery Selector

? In program development, whether it is manipulating the DOM or adding events to elements, it is necessary to obtain the specified element first. To this end, jQuery provides selectors, through which elements can be obtained and manipulated.

1.1 What is a jQuery selector

? The method of obtaining elements through css selectors is very flexible, but after obtaining elements with css selectors, only the style of the element can be manipulated. To add behaviors to elements (such as handling click events), JavaScript code is also required. . To this end, jQuery imitates the css selector to implement the jQuery selector, and obtains elements through the jQuery selector, which not only makes the methods of obtaining elements more diverse, but also adds behavior to the element after obtaining the element.

Syntax:

$(selector);

Characteristics: The methods are more diverse, and behaviors can also be added to elements;

Execution: Returns a jQuery object.

Example:

<div id="myDiv">I am a Div</div>
    <script>
        $('#myDiv').css('border', '1px solid black');
    </script>

Note:

After using the jQuery selector to get the element, since the jQuery object is returned, it can not only add styles to the element, but also support adding behavior to the element. For example, for operations such as binding events to elements, manipulating element attributes, etc., you only need to understand the use of jQuery selectors here.

1.2 Advantages of jQuery selector

Acquisition methods: More concise and more acquisition methods;

Selector: Support from CSS1 to CSS3 and commonly used selectors;

<script>
    //Comparison between DOM and Jquery
    //DOM
    document.getElementById('id value');//Get the element according to the value
    document.getElemtntBtTagName('The name of the element');//Get the element according to the name of the element
    //jQuery
    $('#id value');//Get the element according to the id value
    $('The name of the element');//Get the element according to the name of the element
</script>

2. Basic selector

Basic selectors in jQuery are the simplest and most intuitive selectors, including id selectors, class selectors, element selectors, and wildcard selectors.

Selector Description Return Value strong>
#id id selector single element
.class Class selector Element set
element Element Selector Element Collection
* Wildcard Selector Element Collection
selector1,… Get multiple elements at the same time Element collection
<style>
    div {<!-- -->
        border: 1px solid black;
    }
</style>
<body>
    <div id="byId">First id selector</div>
    <p>the first p element</p>
    <p class="byClass">The first class selector</p>
    <div class="byClass">Second class selector</div>
    <script>
        //id selector
        $('#byId').css('background', 'blue');
        // class selector
        $('.byClass').css('background', 'yellow');
        //element selector
        $('p').css('color', 'blue');
        // wildcard selector
        $('*').css('border', '2px solid red');
        //Get the multi-selector
        $('p,#byId').css("font-weight", 'bold');
    </script>
</body>

Note:

Although wildcard selectors can match all elements, they will affect the rendering time of the web page. Therefore, wildcard selectors should be avoided as far as possible in actual development. Instead, you can use commas in jQuery’s $() when needed to get multiple elements at the same time.

3. Hierarchical selector

The “hierarchy” in the hierarchy selector refers to the hierarchical relationship of DOM elements.

Selector Description Return Value strong>
parent>child child element selector element collection
selector selector1 Descendant selector element collection
pre + next Sibling selector Element set
pre~siblings Sibling selector Element Collection
<p>This is the p element before the div</p>
    <div id="dv">
        <p>This is the p element inside the div</p>
        <ul>
            <li>This is the first li element</li>
            <li><p>This is the p element inside the second li element</p></li>
        </ul>
        <p>This is the second p element in the div</p>
    </div>
    <p>This is the first p element after the div</p>
    <p>This is the second p element after the div</p>
    <p>This is the third p element after the div</p>
    <script>
        // child element selector
        $('#dv > p').css('color','blue');
        // offspring selector
        $('#dv p').css('font-weight','bold');
        //Sibling selector (also known as sibling selector or sibling selector)
            //" + "Get the next adjacent sibling element of the element
        $('#dv + p').css('border','1px solid black');
            //"~"Get all the next adjacent sibling elements of the element
        $('#dv~p').css('text-decoration','underline wavy red');
    </script>

Extension:

(1) children() method

In jQuery, you can also use the children() method instead of the child element selector to get the child elements of the specified element.

<script>
    $('#dv > p');//Use child element selector to get
    $('#dv').children('p');//Use the children() method to obtain
</script>

(2) find() method

In jQuery, you can also use the find() method to get the descendant elements of the specified element.

<script>
    $('#dv p');//Use descendant selector to obtain
    $('#dv').find('p');//Use the find() method to obtain
</script>

(3) Use of next(), nextAll(), prev(), prevAll() and siblings() methods

  • next(): Get the next sibling element next to the specified element;
  • nextAll(): Get all sibling elements after the specified element;
  • prev(): Get the previous sibling element immediately adjacent to the specified element;
  • nextAll(): Get all sibling elements before the specified element;
  • siblings(): You can get all sibling elements of the specified element.
<script>
    //next() method is similar to $('#dv + p')
    $('#dv + p');
    $('#dv').next('p');
    
    //nextAll() method is similar to $('#dv ~ -p')
    $('#dv ~p');
    $('#dv').nextAll('p');
    
    //prev() is the opposite of next(), getting the previous element adjacent to the specified element
    $('#dv').prev('p');
    
    //prevAll() is the opposite of nextAll(), getting all elements before the specified element
    $('#dv').prevAll('p');
    
    //siblings() method is equivalent to the combination of nextAll() and prevAll() to get all the elements of the specified element
</script>

(4) parent() method

  • parent(): Get the parent class of the specified element
<div>
    <p class='app'></p>
</div>
<script>
    $('#app').parent();//Get your own parent class div
</script>

4. Filter selector

Filter selectors: In order to quickly filter DOM elements, jQuery provides some filter selectors.

How to use: Similar to a CSS selector, it starts with “:” and is used to specify rules;

Example: “:first”, used to get the first element.

1. Basic filter selector

Basic filtering selectors: Most of the filtering rules are related to the index value of the element.

Selector Description Return Value strong>
:first Get the first element single element
:last Get the last element Single element
:not(selector ) Get all elements except the selector element set
:even Get all as Odd elements element set
:odd get all even elements element set
:eq(index) Get the element of the specified index value single element
:gt(index) Get all elements greater than the index value element set
:lt( index) Get all elements less than the index value Element set
:header Get the title Elements of type h1… A collection of elements
:animated Get the elements that perform animation Element Collection
 <h1>12</h1>
    <h2>22</h2>
    <ul style="width: 200px;">
        <li>how</li>
        <li class="one">are</li>
        <li>you</li>
        <li></li>
    </ul>
    <p>1</p>
    <p>2</p>
    <p>3</p>
    <p>4</p>
    <p>5</p>
    <p>6</p>
    <script>
        //The index value is even li
        $('li:even').css('backgroundColor', 'pink');
        //The index value is odd li
        $('li:odd').css('backgroundColor', 'yellow');
        //Index except .one element
        $('li:not(.one)').css('border', '1px solid black');
        // index the first element
        $('li:first').css('font-weight', 'bold');
        // index the last element
        $('li:last').css('text-decoration', 'underline wavy red')
        // Get the specified index element to start
        $('p:eq(1)').css('backgroundColor', 'green');
        // Get the element greater than index 2 to start
        $('p:gt(2)').css('font-weight', 'bold');
        // Get the element less than index 2 to start
        $('p:lt(2)').css('font-size', '24px');
        //Get all title elements
        $(':header').css('color', 'blue')
    </script>

2. Visibility selector

In web development, pages with dynamic effects often have many elements hidden. Example: An accordion menu.

Selector Description Return Value strong>
:visible Get all visible elements element set
:hidden Get all invisible elements element set

:hidden selector:

  • The CSS style can be obtained as “display: none”.

  • A text hidden field with the attribute “type=”hidden””.

:visible selector: Gets all visible elements.

<p id="div">Display text 1</p>
    <p id="vis">Display text 2</p>
    <input type="hidden" value="Hidden text field">
    <script>
        //Get all visible elements and color them
        $(':visible').css('backgroundColor', 'yellow');
        //Output the element collection on the console
        console.log($(':visible'));
</script>

:hidden selector: Failed to fetch hidden elements with visibility:hidden.

<p id="div">Display text 1</p>
    <p id="vis">Display text 2</p>
    <input type="hidden" value="Hidden text field">
    <script>
        //Get the displayed p element and set two different hiding methods
        $('#div:visible').css('display', 'none');
        $('#vis:visible').css('visibility', 'hidden');
        //Get the hidden elements and output the element collection on the console
        console.log('hidden p element:');
        console.log($('p:hidden'));
        console.log('hidden field input:');
        console.log($('input: hidden'))
    </script>

Note:

The input hidden field generally does not set the style, but if the CSS style is set to “visibility:hidden” for the input hidden field, the “:hidden” selector can also get the element.

3. Content filter selector

The content of an element refers to the child elements or textual content it contains.

Content filtering selector: Gets elements based on their content.

Selector Description Return Value strong>
:contains(text) Get the element containing the given text element Collection
:empty Get all elements that do not contain child elements or empty elements element collection
:has(selector) Get elements that match the selector element set
:parent Get elements containing child elements or text Element collection
<style>
    div {<!-- -->
        width: 300px;
        height: 30px;
        margin: 5px;
        border: 1px solid black;
    }
</style>

<body>
    <div>I am the text of the div element</div>
    <div>I am also the text of the div element</div>
    <div><span>I am the text of the span element in the div element</span></div>
    <div></div>
    <script>
        //Get the elements that contain the word "also" in the text
        $('div:contains(also)').css('backgroundColor', 'pink');
        / / Get the element that contains the child element span in the text
        $('div:has(span)').css('backgroundColor', 'yellow');
        // get the element without element content
        $('div:empty').css('backgroundColor', 'red');
        // Get the element whose content is not empty
        $('div:parent').css('border', '4px double green');
    </script>
</body>

4. Filter selector

Attribute selector: Filter elements by their attributes.

How to use: jQuery’s attribute filter selector wraps filter rules in “[]”.

Selector Description Return Value strong>
[attribute] Get elements containing the given attribute element collection
[attribute=value] Get elements equal to a given attribute that is a specific value element set
[attribute!=value] Get the elements that are not equal to the given attribute is a specific value element set
[attribute^=value] Get the given attribute is an element starting with some value element set
[attribute$=value] Get elements whose given attribute ends with some value element set
[attribute*=value] Get the given attribute as an element containing some value element set
[selector1][selectorN] Get elements that meet multiple conditions with composite attributes element set
<style>
    div {<!-- -->
        width: 200px;
        margin: 5px;
        border: 1px solid black;
    }
</style>

<body>
    <div class="dv">class=dv</div>
    <div title="title">title=title</div>
    <div class="dv1" title="Title 1">class=dv1 title=Title 1</div>
    <div class="dv1" title="Title 2">class=dv1 title=Title 2</div>
    <script>
        // get the element starting with d
        $('[class^=d]').css('background', 'yellow');
        //Get the element whose class value is dv1 and whose title value contains "2"
        $('[class=dv1][title*=2]').css('border', '4px solid red');
        // get the element ending with title
        $('[title$=题]').css('font-weight', 'bold');
    </script>
</body>

5. Sub-element filter selector

Child element filter selector: Obtain the corresponding element through the corresponding relationship between the parent element and the child element.
Advantages:

  • At the same time, get the child elements that meet the conditions under different parent elements.
  • Compared with the child element selector in the hierarchical selector, it has more flexible filtering rules.
Selector Description Return Value strong>
:first-child Get the first child element under each parent element Element collection
:last-child Get the last child element under each parent element Element collection
:only-child Get the child elements under each parent element with only one child element Element Collection
:nth-child(eq|even|odd|index) Get the specific element index number under each element starting from 1 element set
 <ul>
        <li>Beijing</li>
        <li>Shanghai</li>
    </ul>
    <ul>
        <li>Guangzhou</li>
        <li>Shenzhen</li>
    </ul>
    <ul>
        <li>Tianjin</li>
    </ul>
    <ul>
        <li>chongqing</li>
    </ul>
    <script>
        //Get the first li of each ul list
        //:nth-child's parameter index value starts from 1
        $('li:nth-child(1)').css('border', '1px solid black');
        // Get only one li in each ul list
        $('li:only-child').css('background', 'yellow');
        //Get the first li of each ul list
        $('li:first-child').css('color', 'red');
        //Get the last li of each ul list
        $('li:last-child').css('color', 'green');
    </script>

6. Form filter selector

Form filter selector: It can quickly locate a collection of elements of a certain type in the form on the page.

Selector Description Return Value strong>
:input Get all input|textarea|select|button elements in the form Element Collection
:text Get all input[type=text] elements in the form Element Collection
:password Get all input[type=password] elements in the form element set
:radio Get all input[type=radio] elements in the form element set
: checkbox Get all input[type=checkbox] elements in the form element collection
:submit Get all input[type=submit] elements in the form Single element
:image Get all the elements in the form input[type=image] element element collection
:reset Get all input[type=reset] in the form Element element collection
:button Get all input[type=button] elements and button elements Element collection
:file Get all input[type=file] elements in the form Element collection

Note:

  • :button selector: A button defined using input[type=button] and button elements.
  • :image selector: Images defined with input[type=image] do not include images defined with img.
<form id="myForm">
        Name: <input type="text" value="text"><br>
        Password: <input type="password" value="password"><br>
        Gender: <input type="radio"><span>male</span>
        <input type="radio"><span>female</span><br>
        Hobbies: <input type="checkbox"><span>Swimming</span>
        <input type="checkbox"><span>Travel</span><br>
        Photo 1: <img src="./10001.jpeg" height="200px"><br>
        Photo 2: <input type="image" src="./10001.jpeg" height="150px"><br>
        Description: <textarea></textarea><br>
        <input type="reset" value="reset">
        <input type="submit" value="submit">
        <button>Clear</button>
        <input type="button" value="Save">
    </form>
    <script>
        //: button selector: Get the button and call the hide() method to hide the element.
        $('#myForm :button').hide();
        //:image selector: get the image defined by input[type=image] and hide the image.
        $('#myForm :image').hide();
        //: input selector: get all controls containing input, textarea and hide the matching elements.
        $('#myForm :input').hide();
    </script>

7. Form object attribute filter selector

The form object has some proprietary properties used to represent a certain state of the form.

Form object attribute filter selector: Get the element by object attribute in the form.

Selector Description Return Value strong>
:enable Get all the elements in the form where all attributes are available Element set
:disable Get all elements in the form whose attributes are unavailable element set
:checked Get all selected elements in the form element set
:selected Get all selected option elements in the form element set
<form id="myForm">
        Name: <input type="text" value="text"><br>
        Password: <input type="password" value="password"><br>
    <!--Selected state-->
        Gender: <input type="radio" name="sex" value="male" checked="checked"><span>male</span>
        <input type="radio" name="sex" value="female"><span>female</span><br>
    <!--Selected state-->
        Hobbies: <input type="checkbox" checked="checked"><span>swimming</span>
        <input type="checkbox"><span>Travel</span><br>
        Photo 1: <img src="./10001.jpeg" height="200px"><br>
        Photo 2: <input type="image" src="./10001.jpeg" height="150px"><br>
        Description: <textarea></textarea><br>
        <input type="reset" value="reset">
        <input type="submit" value="submit">
        <button>Clear</button>
        <input type="button" value="Save">
    </form>
    <script>
        //:checked selector: The selector gets the selected element and then hides it.
        $('input: checked').hide();
    </script>