因此,在使用 dom 时,我遇到了这样一种情况,即我假设 document.createTextNode()
生成的对象将以与 生成的对象类似的方式处理document.createElement();
,因为我可以对其调用 setAttribute()
。
例子:
var genericElementNode = document.createElement('p');
genericElementNode.setAttribute('id', 'sampleId1');
// The above will run fine
var textNode = document.createTextNode("Hello World");
textNode.setAttribute('id', 'sampleId2');
//The above will result in an error:
//Uncaught TypeError: textNode.setAttribute is not a function
为什么会这样?有什么解决方法吗?
最佳答案
您不能设置/获取 textNode 的任何属性/元素
are there any workarounds?
在span
中创建元素并设置文本很容易
var genericElementNode = document.createElement('p');
genericElementNode.setAttribute('id', 'sampleId1');
// The above will run fine
var textNode = document.createElement("span");
textNode.innerText = "Hello World";
textNode.setAttribute('id', 'sampleId2');
关于javascript - 为什么 document.createTextNode() 不允许 setAttribute()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40151114/