【问题标题】:Parse the DOM to remove all attributes of x and all classes of y解析 DOM 以删除 x 的所有属性和 y 的所有类
【发布时间】:2021-04-20 23:45:17
【问题描述】:

我正在使用打字稿来调整模板化的 html 构建文件。在我的 TS 文件中,我有以下代码:

let body = document.querySelector("body");

// Looking at using this to remove all attributes of certain types/names
[...elem.attributes].forEach(attr => elem.removeAttribute(attr.name))

body 变量是来自 DOM 的 BodyElement,可以很好地提取它。我需要解析所有元素以删除名为:

click.delegate="doSomething();"
show.bind="toggle();"

和班级:

aurelia-hide

如果在 TS 中通过一次 forEach 快速摆脱这一切,那就太好了。

【问题讨论】:

  • 旁注:document.body 可用。您不必查找它
  • 但是elem 是在哪里定义的?
  • 如果你想从所有元素中删除一个属性,我建议你做document.querySelectorAll('[theAttribute]'),然后你会得到一个只有具有该属性的元素的列表。
  • 我想循环遍历作为 BodyElement 的主体(让 body = ...)并删除所有提到的属性和类,然后使用 body.innerHTML 构建一个新的 HTML 文件。跨度>

标签: javascript html typescript ecmascript-6 aurelia


【解决方案1】:

看看这个sn-p:

const removeClassElement = document.getElementById('1');
removeClassElement.className = "";
// or classList = "" or classList = null or classList.remove(...removeClassElement.classList);
console.log(removeClassElement);

const removeAttributes = document.getElementById('2');
[...removeAttributes.attributes].forEach(attr => removeAttributes.removeAttribute(attr.name));
console.log(removeAttributes);
<p id="1" class="one two three">Lorem ipsum dolor sit amet</p>
<p id="2" style="color: green; font-weight: bold" title="title">Lorem ipsum dolor sit amet</p>

【讨论】:

  • [... 在 TS/JS 中有什么特别之处吗?只是好奇。
  • "..." 是 JS 是“spread”或“rest”运算符/语法。扩展语法将数组“扩展”为其元素,而其余语法收集多个元素并将它们“压缩”为单个元素。当您需要将参数列表传递给函数但您有一个数组时,执行数组/对象的浅拷贝之类的操作非常方便,对于对象的不变性,最重要的是,它可以帮助开发人员交付更少的(必要的!)代码
猜你喜欢
  • 1970-01-01
  • 2021-03-18
  • 2020-12-06
  • 1970-01-01
  • 2015-05-21
  • 2022-01-22
  • 1970-01-01
  • 2012-07-12
  • 1970-01-01
相关资源
最近更新 更多