贝壳 - BeiKe 贝壳 - BeiKe - 5 months ago 11
CSS Question

How do I keep all ul and li's under a parent li:selected, but remove other navigation items

I need to only keep the UL & LIs under the selected parent, but remove any others that occur before or after.

For example, given:

<ul id="fruit">
<li class="selected"> Red </li>
<ul> Sweet </ul>
<li> Cherry </li>
<li> Apple </li>
<ul> Tart </ul>
<li> Yellow <li>
<li> Green </li>


I need:

<li class="selected"> Red </li>
<ul> Sweet </ul>
<li> Cherry </li>
<li> Apple </li>
<ul> Tart </ul>


I have tried $(".fruit li:not(.selected)"); however that removes all the children li and ul included. I also tried

$( document ).ready(function() {

$('.s4-ql li').each(function(){
if($(this).parent.attr('selected') == 'selected'){
$(this).css("display", "initial");
}
else {
$(this).css("display", "none");

}
});


Thanks!

Answer

Assuming you correct your HTML to valid HTML like this:

<ul id="fruit">
    <li class="selected"> Red 
        <ul>
            <li> Sweet </li>
            <li> Cherry </li>
            <li> Apple </li>
            <li> Tart</li> 
      </ul>
    </li>
    <li> Yellow </li>
    <li> Green </li>
</ul>

Then you can detach your selected like this.

var $selected = $('#fruit').find('.selected').detach();

It's a simple remove() of the $('#fruit') from there and your selected is the part you wanted to keep. https://jsfiddle.net/n25qbmLo/

It looks like your Sweet and Tart are subheaders so if that's true your HTML should be like this:

<ul id="fruit">
    <li class="selected"> Red 
        <ul>
          <li> Sweet 
              <ul>
                <li> Cherry </li>
                <li> Apple </li>
              </ul>
          </li>
          <li> Tart</li> 
      </ul>
    </li>
    <li> Yellow </li>
    <li> Green </li>
</ul>

https://jsfiddle.net/n25qbmLo/2/

Comments