javascript - 为什么 document.createTextNode() 不允许 setAttribute()?

标签 javascript

因此,在使用 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/

相关文章:

javascript - 在 chrome 扩展中使用 channel google app engine

javascript - 如何在 JavaScript 中构建 Websocket 数据

javascript - Grunt - 警告 : Task "default" not found. 使用 --force 继续

javascript - 原生 Android 浏览器的 Bootstrap 模式在触摸时关闭

javascript - 遍历我的主目录时出现 EPERM 错误的原因是什么?

javascript - 有没有办法使用 javascript 或 Jquery 找出某人计算机上屏幕的宽度?

internet-explorer-8 - 如何使用 Javascript 检测 IE7/IE8 "run as administrator"模式

javascript - 如果原型(prototype)继承提供了一切,为什么还要使用 Javascript 命名空间

javascript - 如何在 JavaScript Web Worker 中异步解压缩 gzip 文件?

javascript - 通过 Typescript 类扩展 JavaScript 对象原型(prototype)