【问题标题】:How to get the original case of element names in (X)HTML DOM in javascript?如何在javascript中获取(X)HTML DOM中元素名称的原始大小写?
【发布时间】:2022-10-15 12:59:28
【问题描述】:

我读到 HTML 总是从 Node.prototype.nodeName 和 HTMLElement.prototype.tagName 全部变成大写,但不是 HTML 的 XML 元素保留在原来的大小写中。

这不是我发现的。一切都变成了大写字母,尖叫着“我们仍停留在 1980 年代!”在我们的脸上。

<html>
  <body>
    <script>
const e = document.createElement('fooBar');
document.firstElementChild.insertBefore(e, document.firstElementChild.firstElementChild);
    </script>
    <p>
      <span>Hello</span>
      <script>
         document.currentScript.parentElement.firstElementChild.innerText = e.nodeName;
      </script>
    </p>
  </body>
</html>

现在真正的真相是什么?

如何恢复原案?

如何保存案例?

我知道我可以创建一个new Document(),然后我在其中创建的节点仍然区分大小写。

我想如果我将 HTML 文档声明为 XHTML,它应该是小写并保留大小写。如何在 HTML DOM 中保留 XML 的大小写?

【问题讨论】:

  • 创建非标准元素并将其放入 HTML DOM 不会使其成为 XML 元素。
  • 这看起来像XY Problem。您提供的高度人为的示例很可能不能很好地代表实际问题。请专注于实际问题。

标签: javascript html xml dom xhtml


【解决方案1】:

确保该元素不是 HTML 元素。所以使用createElementNS 而不是createElement。命名空间不能是 HTML 命名空间。空字符串就可以了。

<!DOCTYPE html>
<html>
  <body>
    <script>
const e = document.createElementNS('', 'fooBar');
document.firstElementChild.insertBefore(e, document.firstElementChild.firstElementChild);
    </script>
    <p>
      <span>Hello</span>
      <script>
         document.currentScript.parentElement.firstElementChild.innerText = e.nodeName;
      </script>
    </p>
  </body>
</html>

【讨论】:

    猜你喜欢
    • 2014-07-26
    • 2010-12-18
    • 2018-11-12
    • 1970-01-01
    • 1970-01-01
    • 2013-01-22
    • 2017-05-01
    • 1970-01-01
    相关资源
    最近更新 更多