Remove double bullets in nested list

2019-02-21 19:37发布

问题:

Nested list have double bullets. One for the li and another for the child list.

example

    <ul>
        <li>item</li>
        <li>item</li>
        <li>
            <ul>
                <li>item</li>
                <li>item</li>
                <li>item</li>
            </ul>
        </li>
    </ul>

回答1:

You can’t do this just in an external style sheet (as I presume you would want to). The reason is that there is no selector in CSS that would pick up those li elements that have a ul element as the first child. So your options are (apart from waiting indefinitely until CSS has a “parent selector”...):

  • Add class to such li elements and use a class selector. This is normally the preferred way.
  • Use JavaScript that recognizes such li elements and handles them, e.g. adding a class to them.
  • Use inline CSS, i.e. style attribute in those li elements.


回答2:

The nested list should be a child of one of the list items, like so:

<ul>
  <li>item</li>
  <li>item
    <ul>
      <li>item</li>
    </ul>
  </li>
</ul>

This is valid HTML.



回答3:

Would you mind if I used styles? Updated

Code:

        <ul>
            <li>item</li>
            <li>item</li>
            <li style="list-style:none">
                <ul>
                    <li>item</li>
                    <li>item</li>
                    <li>item</li>
                </ul>
            </li>
        </ul>
        <ol>
            <li>item</li>
            <li>item</li>
            <li style="list-style:none"><ol>
                    <li>item</li>
                    <li>item</li>
                    <li>item</li>
                </ol>
            </li>
        </ol>

Another method might be running through the list of LI and adding the style by detecting child nodes. Example

Code (HTML is the same):

var li = document.getElementsByTagName("li");

for (var i=0, max=li.length; i < max; i++)
    if (li[i].childNodes.length > 1)
        li[i].style.listStyle = "none";


回答4:

quick hack: remove the list item:

<ul>
    <li>item
    <li>item
    <ul>
         <li>item
         <li>item
         <li>item
    </ul>
</ul>

if you don't close the tags the browser will render it correctly, that is without the extra bullet. Note: this is valid html since you don't need to close <li> tags.

JSFIDDLE with both examples

source: Google

"as opposed to XHTML, even when delivered with the MIME type text/html – allows authors to omit certain tags."

from google:

if you have a list of items marked up as <li>List item</li>, you could instead just write <li>List item...

Omitting optional tags keeps your HTML formally valid...