Home > Article > Web Front-end > How to Target Only Immediate Children with CSS Selectors: A Comprehensive Guide
How to Target Only Immediate Children with CSS Selectors
When working with nested elements, it can be challenging to style only the immediate children and exclude all descendants. Traditional CSS selectors like ul > li and #parent > li will include all child elements, regardless of their nesting level.
Immediate Child Selector in CSS
The immediate child selector > can be used to target only the first-level children of a parent element. For example, to target only the top-level list items in your nested sortable list, you can use the following selector:
#parent > li
Note: This selector is not supported in IE6.
Workaround for IE6
For backward compatibility with IE6, you can use the following CSS hack:
#parent li { /* your styles for immediate children */ } #parent li li { /* reset styles for descendants */ }
MooTools-Specific Solution
In your MooTools-based code, the issue arises because getElements() retrieves all descendants instead of just immediate children. To fix this, you can use getChildren() instead:
var drop = function(el){ el.getParents('ul').reverse().each(function(item){ var posCount = 1; item.getChildren("li").getElements("a span[class=position]").each(function(pos){ pos.set('text', posCount); posCount++; }); }); };
By using getChildren(), you can ensure that the position text is updated correctly for only the immediate children of each nested list.
The above is the detailed content of How to Target Only Immediate Children with CSS Selectors: A Comprehensive Guide. For more information, please follow other related articles on the PHP Chinese website!