• ...">

    Choosing the first instance of a class but not nested instances via jQuery

    Given the following hypothetical markup:

    <ul class="monkey">
        <li>
            <p class="horse"></p>
            <p class="cow"></p>
        </li>
    </ul>
    
    <dl class="monkey">
        <dt class="horse"></dt>
        <dd class="cow">
            <dl>
                <dt></dt>
                <dd></dd>
            </dl>
            <dl class="monkey">
                <dt class="horse"></dt>
                <dd class="cow"></dd>
            </dl>
        </dd>
    </dl>
    

    I want to be able to capture the β€œfirst level” horse and cow classes in each monkey class. But I do not want the classes of horses and cows NESTAD.

    I started with .children, but this will not work with the UL example, since they are not direct children of .monkey.

    I can use find: $ ('. Monkey'). find ('. horse, .cow'), but returns all instances, including nested ones.

    I can filter find: $ ('. Monkey'). find ('. horse, .cow'). not ('. cow.horse, .cow.cow'), but this prevents me from choosing nested instances when calling the second function.

    ... , , " " . , , / - , .

    UPDATE:

    :

    $('.monkey')
        .children('.cow')
            ...do something...
        .end()
        .children('li')
            .children('.cow')
                ...do something...
            .end()
        .end()
    

    /, , , .

    +3
    4

    , .

    $(".monkey").children(".horse, .cow, li > .horse, li > .cow")
    

    Edited

    $(".monkey, .monkey > li").children(".horse, .cow")
    
    +3
    $('.monkey .horse:first')
    

    http://api.jquery.com/first-selector/

    0

    , - ?

    $('.monkey>.horse, .monkey>.cow')
    

    .monkey, , .monkey .

    0

    This is the correct selector that will allow you to return only the first children of li and dt .

    var selection = $(".monkey > * > .horse, .monkey > * > .cow");
    
    0
    source

    Source: https://habr.com/ru/post/1744364/


    All Articles