Does the <Li> Tag in HTML Have an Ending Tag

Does the li tag in HTML have an ending tag?

The li element has an end tag (</li>), but it’s optional in some cases:

An li element's end tag may be omitted if the li element is immediately followed by another li element or if there is no more content in the parent element.

Why does this HTML not have a closing li tag?

The end tag for a <li> is optional. If you don't put it in explicitly it will be automatically inserted before the next <li> or </ul> (or </ol>).

If you insert it manually before the <ul> then you are moving the nested <ul> so it is no longer inside the <li>.

Instead, you try to create the <ul> as a child element of another <ul> which is forbidden in HTML.

Is a self-closing li tag valid?

No, it isn't. You can test this with a validator.

The / is an error so browsers will ignore it, treating it as a start tag.

The <p> elements are therefore children of the <li> elements (which they have to be since they aren't allowed to be children of <ul> elements).

The next <li> (or </ul>) implicitly ends the previous <li> because the end tag is optional for that element.

When is a closing /li not optional?

So, what W3C is saying is

An li element’s end tag is mandatory if the li element is immediately followed by something else than another li element or if there is more content in the parent element.

How is this possible? li Elements can only occur within ols, uls and menus.
But ols und uls allow only lis as their children.

What about menu? It allows flow content too. So there you have it:

<menu>
<li>foo</li> <!-- mandatory -->
<a href="//example.com">bar</a>
</menu>

<menu>
<li>foo</li> <!-- mandatory -->
Hello, I am text content!
</menu>

When you see the examples it is pretty obvious that omitting the end tag would give the parser no chance to determine where the li ends.


Edit: as @BoltClock points out below, script and template elements are now allowed too:

<ul> <!-- or ol or menu -->
<li>foo</li> <!-- mandatory -->
<script></script>
</ul>

Replacing li tag if it's opening and closing tag lies in between span opening and closing tag

This regex did the trick for me. Just swap second subgroup ($2) with whatever.
For example:

$html = 'lol <span style="background-color:limegreen;"> <br /> <li> this </li>  </span> <br /> this is something <li"> This is new </li>';
$html = preg_replace('/(<span.+>.+)(<li>)(.+<\/li>.+<\/span>)/', '$1 replacement $3', $html);

result:

lol <span style="background-color:limegreen;"> <br />  replacement  this </li>  </span> <br /> this is something <li"> This is new </li>

Change replacement to whatever you need.

Nuxt generate not closing tags

HTML produced by nuxt is minified. And since closing li is optional, it's stripped.



Related Topics



Leave a reply



Submit