Selecting only first-level elements in jquery

前端 未结 10 2162
忘了有多久
忘了有多久 2020-11-28 03:14

How can I select the link elements of only the parent

    from a list like this?

    • Link
相关标签:
10条回答
  • 2020-11-28 03:59

    I had some trouble with nested classes from any depth so I figured this out. It will select only the first level it encounters of a containing Jquery Object:

    var $elementsAll = $("#container").find(".fooClass");4
    
    var $levelOneElements = $elementsAll.not($elementsAll.children().find($elementsAll));
    
    $levelOneElements.css({"color":"red"})
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <div class="fooClass" style="color:black">
    Container
      <div id="container">
        <div class="fooClass" style="color:black">
          Level One
          <div>
            <div class="fooClass" style="color:black">
                 Level Two
            </div>
          </div>
        </div>
        <div class="fooClass" style="color:black">
          Level One
          <div>
            <div class="fooClass" style="color:black">
                 Level Two
            </div>
          </div>
        </div>
      </div>
    </div>

    0 讨论(0)
  • 2020-11-28 04:03

    You might want to try this if results still flows down to children, in many cases JQuery will still apply to children.

    $("ul.rootlist > li > a")
    

    Using this method: E > F Matches any F element that is a child of an element E.

    Tells JQuery to look only for explicit children. http://www.w3.org/TR/CSS2/selector.html

    0 讨论(0)
  • 2020-11-28 04:08

    You can also use $("ul li:first-child") to only get the direct children of the UL.

    I agree though, you need an ID or something else to identify the main UL otherwise it will just select them all. If you had a div with an ID around the UL the easiest thing to do would be$("#someDiv > ul > li")

    0 讨论(0)
  • 2020-11-28 04:11

    1

     $("ul.rootlist > target-element")
    2   $("ul.rootlist").find(target-element).eq(0) (only one instance)
    3   $("ul.rootlist").children(target-element)
    

    there are probably many other ways

    0 讨论(0)
提交回复
热议问题