[jquery] Selecting only first-level elements in jquery

How can I select the link elements of only the parent <ul> from a list like this?

<ul>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a>
  <ul>
    <li><a href="#">Link</a></li>
    <li><a href="#">Link</a></li>
    <li><a href="#">Link</a></li>
    <li><a href="#">Link</a></li>
    <li><a href="#">Link</a></li>
  </ul>
</li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>

So in css ul li a, but not ul li ul li a

Thanks

This question is related to jquery html css css-selectors

The answer is


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")


.add_to_cart >>> .form-item:eq(1)

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


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');

Simply you can use this..

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

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


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


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


Try this:

$("#myId > UL > LI")

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:

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


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.


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to css-selectors

Angular 2: How to style host element of the component? How to click a href link using Selenium How do I apply a style to all children of an element How to write a CSS hack for IE 11? :last-child not working as expected? Need to find element in selenium by css jQuery select child element by class with unknown path How do I select an element that has a certain class? What is the difference between cssSelector & Xpath and which is better with respect to performance for cross browser testing? What is the mouse down selector in CSS?