为什么 ::before CSS 选择器在动态添加项目时不适用于列表项?

Why does ::before CSS Selector not work with list items when a item is added dynamically?

我有以下列表:

<ul id="objects-list">
   <li>Table</li>
   <li>Chair</li>
   <li>Window</li>
</ul>

具有以下 CSS(取自 https://www.w3schools.com/howto/howto_css_bullet_color.asp):

ul {
  list-style: none;
}

ul li::before {
  content: "22";
  color: red;
  font-weight: bold;
  display: inline-block; 
  width: 1em;
}

这会将默认列表标记更改为红色。 一切正常,但是当我通过 Javascript 使用

将新项目添加到列表时
var objectsList = document.getElementById("objects-list");
var listItem = document.createElement("LI");
listItem.innerHTML = "Pen";
objectsList.appendChild(listItem );

它发生在我的 XHTML 文件中。它不会发生在 Stack Snippet 中。

该项目已正确添加到列表中,但根本没有任何标记。此外,当我在检查器中检查新项目时,它根本没有显示“::before”元素。

谁能解释一下为什么?

我已经使用 XHTML 文件成功地复制了您的问题。

问题在于 XHTML 区分大小写li != LI。更改添加元素的代码以使用 li:

var listItem = document.createElement("li");
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^

这里有一个完整的 XHTML 文件演示了这个问题。如果您想在本地验证它,请确保使用正确的 Content-Type 提供文件(使用扩展名 .xhtml 并从文件系统打开它也可以,至少在 Chrome 和它的变体):

<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>XHTML CSS Problem</title>
<style>
ul {
    list-style: none;
}

ul li::before {
    content: "22";
    color: red;
    font-weight: bold;
    display: inline-block; 
    width: 1em;
}
</style>
</head>
<body>
<ul id="objects-list">
   <li>Table</li>
   <li>Chair</li>
   <li>Window</li>
</ul>
<script>
var objectsList = document.getElementById("objects-list");
var listItem = document.createElement("LI");
listItem.innerHTML = "Pen";
objectsList.appendChild(listItem );
</script>
</body>
</html>