Selecting children elements but NOT grandchildren
Use the CSS Greater than sign >
(Child selectors):
#content > p
A child selector matches when an element is the child of some element.
Choosing Children but not grandchildren with Jquery
$('#parent').children('>ul');
The above would not work with the markup in the question.
You want the child selector
You'd need the following:
$('#parent > li > ul');
CSS: Select all first generation elements (children), but not grandchildren
You could use
:not(li) > ul > li {
border: 1px solid red;
}
which means target the li
in a ul
that is not contained (directly) in a li
.
So keep in mind that if inside a li you add a div
and in that a ul li
it will get styled.
:not(li) > ul > li { border: 1px solid red;}
<ul> <li>Level One Item One <ul> <li>Level One Item One</li> <li>Level One Item Two</li> </ul> </li> <li>Level One Item Two <ul> <li>Level Two Item One</li> <li>Level Two Item Two</li> </ul> </li></ul>
Selecting items with children but not grandchildren using jQuery selectors
Use a descendent selector.
$("#parent > li:has(ul)").hoverIntent( showSubNav, hideSubNav );
This will only do $.hoverIntent()
on immediate children li
s that have a child ul
.
If you want to show the adjacent ul
when you hover over the <a>
, then this:
$('#parent > li > a').hover(function() {
$(this).next('ul').addClass();
});
Hovering over a top level <li>
and then add a class to it's immediate <ul>
child:
$('#parent > li').hover(function() {
$(this).child('ul').addClass();
});
querySelectorAll select children but not grandchildren Vanilla Javascript
You can filter element's children. Working demo.
// matchSelector
var matches = (function(p){
return p.matches
|| p.webkitMatchesSelector
|| p.mozMatchesSelector
|| p.msMatchesSelector
}(Element.prototype))
var layers = [].filter.call(element.children, function(el) {
return matches.call(el, '.layer')
});
selecting the first child of a list without including the grandchildren
Try:
.parent > ul > li:first-child
{
color:blue;
}
.parent > ul > li:last-child
{
color:red;
}
This way, you are selecting the first li
and the last li
that comes directly inside the child ul
of the .parent
div.
CHECK IT OUT
Related Topics
Extra Padding in Select Option Element in Chrome
Angular: Transclusion, Set Color of Svg Element
Display:Table-Cell Not Working in Ie9
Bootstrap Dropdown Menu Text Color
How to "Hack" The Thunderbird Lightning Extension to Fully Color Categories
An Alternative to -Webkit-Transform: Transformy
Sass: Selecting The Parent Element with Multiple Nested Selectors
How to Specify Image Paths in CSS Files
How to Make a Blinking Image in CSS3
CSS - Border Radius and Solid Border Curved Inside
Using @Import for Google Fonts Is Not Working on Internet Explorer
Bootstrap - Spacing Between Form-Inline Elements
Can a CSS Pseudo-Class Be Namespaced
Max-Width:-Webkit-Fit-Content Ie 8 Equivalent
How to Use Liquid Tags in CSS to Have Jekyll Use a Different Background Image on a Per-Page Basis