jq filtering method

Filtering is to find the desired element from the set of matching elements. (from a bunch of elements)
1. first() and last()
Syntax: $(selector).first()
Gets the first element in the matching element collection. This method does not accept any parameters.
Syntax: $(selector).last()
Gets the last element in the matching element collection. This method does not accept any parameters.

<ul>
    <li>list item 1</li>
    <li>list item 2</li>
    <li>list item 3</li>
</ul>
<p>
    <span>Look:</span>
    <span>This is some text in a paragraph.</span>
    <span>This is a note about it.</span>
</p>
<script>
    $("li").first().css("background-color", "red");
    $("p span").first().addClass('highlight');
</script>

2. filter() and not() and has()
Filter: filter out what you need
not: the antonym of filter, filter out the unnecessary
has: contains

 <ul id="list">
        <li> <span class="a">I am span</span> 111111</li>
        <li class="a">2222222</li>
        <li>33333333</li>
        <li class="b">4444444</li>
        <li class="a">5555555555</li>
    </ul>

    <script>
        //$("ා list li"). CSS ("background color",'Red '); / / all li will change
        //$("ා list li"). Filter ('. a'). CSS ("background color",'Red '); / / li with. a will
        //$("ාlist li"). Not ('. a'). CSS ("background color",'Red '); / / li without. a
        $("#list li "). Has ('. a'). CSS ('background color','Red '); / / li with. a in child element
    </script>

3.eq()
Subscript starts at 0

    <h1>I'm the title 00000</h1>
    <div class="box">
        <p>111111</p>
        <p>2222</p>
        <div>
            <p>333</p>
        </div>
        <p class="selected">444444</p>
        <h1>I'm Title 1111</h1>
    </div>

    <script>
        $("h1").eq(1).css('color','blue')
        $(".box").find("p").eq(3).css('color','red')
    </script>
    4. index() method

Index is the position of the current element in all sibling nodes, starting from 0 (that is, the position of the current element in a group of elements, and the current element and this group of elements are siblings of the same level)

<div>
    <h1>11111</h1>
    <h2>222222222</h2>
    <h1>333333333</h1>
    <h2 id="hhh">444444444444</h2>
    <h1>555555555555</h1>
    <p>666666666</p>
</div>
<h2>7777777777</h2>
<script>
    $(function(){
        alert($('#hhh').index()); // 3
    });
</script>

Tags: Javascript

Posted on Thu, 04 Jun 2020 09:01:53 -0700 by knox203