CSS selector for targeting only immediate children and not other identical descendants

前端 未结 2 743
心在旅途
心在旅途 2020-11-29 10:12

I have a nested sortable list that can have items dynamically added or removed and can be nested n-levels deep. On nesting, a new ul element is injected into whatever li ele

相关标签:
2条回答
  • 2020-11-29 10:44
    ul > li
    

    only does the immediate children. So, for example, to do only the top level list elements you could use:

    #parent > li
    

    Note: this isn't supported on IE6.

    The common workaround for backwards compatibility is to do something like this:

    #parent li { /* style appropriately */ }
    #parent li li { /* back to normal */ }
    

    It's more tedious because you have to apply styles and then turn them off (and you may not necessarily know what the old values are) but it's the only IE6-friendly pure CSS workaround there is.

    Edit: Ok you have a MooTools specific issue. getElements() returns all descendants, not just immediate children. Try using getChildren().

    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++;
            });
        });
    }
    

    or something like that.

    0 讨论(0)
  • 2020-11-29 10:44

    The original question was not answered. :only-child only works if the only-child has no descendant children. The original post suggested that the inclusion of descendant children was due to ul>li whereas it is in fact due to a bug in :only-child. Paradoxically :first-child selects the first child in a list with descendant children, as does last-child, but :only-child does not. I checked this in Firefox, Opera and Chrome. Here is an example:

    <!DOCTYPE html>
    <html lang="en">
    <head><meta charset="utf-8">
    <style>
    .list>ul>li:only-child {color:red}
    .list>ul>li:first-child {color:green}
    .list>ul>li:last-child {color:blue}
    </style>
    </head>
    <body>
    <div class="list">
    <ul><li>Item one</li><ul>
    <l>Subitem one</li>
    <li>Subitem two</li></ul></li><!--<li>Item two</li>
    <li>Item three</li>-->
    </ul></div>
    </body></html>
    

    To activate :first-child and :last-child rules uncomment the last two items. The implementation of the Selectors Level 3 standard is thus inconsistent in major browsers. The :first-child rule should not be activated when there is an :only-child rule and a unique child has descendants. In the example the only-child should be red but it is green.

    0 讨论(0)
提交回复
热议问题