How can I select the link elements of only the parent
from a list like this?
Try this:
$("#myId > UL > LI")
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');
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.
.add_to_cart >>> .form-item:eq(1)
the second .form-item at tree level child from the .add_to_cart
Simply you can use this..
$("ul li a").click(function() {
$(this).parent().find(">ul")...Something;
}
See example : https://codepen.io/gmkhussain/pen/XzjgRE
$("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