Home >Web Front-end >CSS Tutorial >How to Target Only Immediate Children in a Nested List with CSS Selectors?

How to Target Only Immediate Children in a Nested List with CSS Selectors?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-09 00:50:01380browse

How to Target Only Immediate Children in a Nested List with CSS Selectors?

CSS Selector for Identifying Immediate Children

In CSS, the purpose of a child selector is to target elements that are the immediate descendants of a specified parent element. However, the selector ul > li can inadvertently select all li elements that are descendants of a ul, not just the immediate children.

Answer: Using Immediate Child Selector

The correct CSS selector to ensure only the immediate children of a ul are targeted is ul > li. This selector specifies that the li elements should be directly descended from the ul, excluding any elements nested within sublists.

Applying the Selector in MooTools

In the provided MooTools code, getElements() returns all descendants, including deeply nested elements. To remedy this, the code should utilize 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++;
        });
    });
}

Additional Considerations

  • IE6 Compatibility: The > selector is not supported in IE6. A workaround is to use the following CSS:
#parent li { /* style appropriately */ }
#parent li li { /* back to normal */ }
  • Nested Elements: If the li elements contain further nested elements, additional selectors may be necessary to target specific sublevels.

Conclusion

By employing the > selector, the MooTools code will accurately update the positions of immediate children li elements when items are sorted or moved. This ensures that the numbering within the nested sortable list is correct and reflects only the changes made to the top-level elements.

The above is the detailed content of How to Target Only Immediate Children in a Nested List with CSS Selectors?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn