我根据以下链接提出这个问题:https://developer.mozilla.org/en-US/docs/Web/API/Attr
我看到很多开发人员使用这些方法,老实说,我不完全确定它们是否真的被整体弃用或仅在特定上下文中被弃用。不管怎样,它确实将它们列为已弃用,这就是为什么我要问:有哪些有效且最新的替代方案?特别适用于:
removeChild、textContent、appendChild。甚至 insertBefore 也已被弃用。
最佳答案
我的猜测是你很困惑node
对象和 attribute
对象。您命名的函数通常与前者一起使用,但不适用于后者。 MDN 文章仅描述 attribute
对象。
了解更多信息:
一个<div>
是一个节点,它可以有一个属性 data-foo="bar"
在上面。
向节点追加子节点或修改文本是很常见的。例如,给定:
var node = document.createElement('div');
node.innerHTML = '<p>Hello</p><p> World</p>';
node.removeChild(node.firstChild);
将生成 HTML <div><p> World</p></div>
但是,这对于属性来说并没有真正的意义。属性本质上只是附加到节点的字符串。与属性一起使用的常见操作是 name
和value
。例如:
var node = document.createElement('div');
node.setAttribute('data-foo', 'bar');
var attr = node.getAttributeNode('data-foo');
console.log(attr.name); // prints 'data-foo'
console.log(attr.value); // prints 'bar'
console.log(typeof attr); // prints 'object'
至少就我个人而言,我很少使用 Attr
对象,而不是 node.getAttribute('data-foo')
返回 string
的bar
,这足以满足我的需求。
至于为什么这些方法首先存在于attr
上对象,我将简单地从您链接的 MDN 文章中复制/粘贴:
Warning: In DOM Core 1, 2 and 3, Attr inherited from Node. This is no longer the case in DOM4. In order to bring the implementation of Attr up to specification, work is underway to change it to no longer inherit from Node. You should not be using any Node properties or methods on Attr objects.
关于javascript - 不推荐使用removeChild、textContent 和appendChild。备择方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35644807/