Selecting only first-level elements in jquery

前端 未结 10 2161
忘了有多久
忘了有多久 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:45

    Try this:

    $("#myId > UL > LI")
    
    0 讨论(0)
  • 2020-11-28 03:46

    Once you have the initial ul, you can use the children() method, which will only consider the immediate children of the element. As @activa points out, one way to easily select the root element is to give it a class or an id. The following assumes you have a root ul with id root.

    $('ul#root').children('li');
    
    0 讨论(0)
  • As stated in other answers, the simplest method is to uniquely identify the root element (by ID or class name) and use the direct descendent selector.

    $('ul.topMenu > li > a')
    

    However, I came across this question in search of a solution which would work on unnamed elements at varying depths of the DOM.

    This can be achieved by checking each element, and ensuring it does not have a parent in the list of matched elements. Here is my solution, wrapped in a jQuery selector 'topmost'.

    jQuery.extend(jQuery.expr[':'], {
      topmost: function (e, index, match, array) {
        for (var i = 0; i < array.length; i++) {
          if (array[i] !== false && $(e).parents().index(array[i]) >= 0) {
            return false;
          }
        }
        return true;
      }
    });
    

    Utilizing this, the solution to the original post is:

    $('ul:topmost > li > a')
    
    // Or, more simply:
    $('li:topmost > a')
    

    Complete jsFiddle available here.

    0 讨论(0)
  • .add_to_cart >>> .form-item:eq(1)
    

    the second .form-item at tree level child from the .add_to_cart

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

    Simply you can use this..

    $("ul li a").click(function() {
      $(this).parent().find(">ul")...Something;
    }
    

    See example : https://codepen.io/gmkhussain/pen/XzjgRE

    0 讨论(0)
  • 2020-11-28 03:58
    $("ul > li a")
    

    But you would need to set a class on the root ul if you specifically want to target the outermost ul:

    <ul class="rootlist">
    ...
    

    Then it's:

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

    Another way of making sure you only have the root li elements:

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

    It looks kludgy, but it should do the trick

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