如何在document.createElement("span");?之后将文本添加到span中

Joe*_*Joe 15 javascript jquery dom

我正在尝试使用函数.text()将文本写入元素范围,但是我收到此错误 UncaughtTypeError:undefined不是函数,我还尝试了函数append(),innerHtml(),createTextNode()但没有成功.

我究竟做错了什么?

var closeSpan = document.createElement("span");
closeSpan.setAttribute("class","sr-only");
closeSpan.text("Close"); //UncaughtTypeError: undefined is not a function
Run Code Online (Sandbox Code Playgroud)

要么

var closeSpan = document.createElement("span");
closeSpan.setAttribute("class","sr-only");
closeSpan.append("Close"); //UncaughtTypeError: undefined is not a function
Run Code Online (Sandbox Code Playgroud)

Lou*_*uis 33

由于您从纯DOM代码开始,我建议继续使用纯DOM代码:

var closeSpan = document.createElement("span");
closeSpan.setAttribute("class","sr-only");
closeSpan.textContent = "Close";
Run Code Online (Sandbox Code Playgroud)

换句话说,只需设置textContent您想要的值.

如果与IE 8或更早版本的兼容性对您很重要,请注意textContent那些旧版浏览器不存在.对于那些你必须使用的旧版本innerText(适用于IE 8,但不是任何标准的一部分)或innerHTML.有关textContent这些字段之间差异的讨论,请参阅MDN页面(我链接到上面).


Sea*_*ean 5

如果你希望使用jQuery的,你可以使用closeSpan.appendChilddocument.createTextNode像这样:

var closeSpan = document.createElement("span");
closeSpan.setAttribute("class","sr-only");
closeSpan.appendChild(document.createTextNode("Close"));
Run Code Online (Sandbox Code Playgroud)

这种方法最大限度地提高了跨浏览器的兼容性。它适用于所有浏览器,包括旧版本的 IE。

如果您确实想使用 jquery,可以在一行中执行此操作:

var closeSpan = $("<span></span>").addClass("sr-only").text("Close")[0];
Run Code Online (Sandbox Code Playgroud)