How to add text to a range after document.createElement ("span");?

I am trying to write text in a span of an element with the function .text (), but I got this error UncaughtTypeError: undefined is not a function , and I also unsuccessfully tried to use the functions append (), innerHtml (), createTextNode ().

What am I doing wrong?

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

OR

 var closeSpan = document.createElement("span"); closeSpan.setAttribute("class","sr-only"); closeSpan.append("Close"); //UncaughtTypeError: undefined is not a function 
+5
source share
4 answers

Since you start with pure DOM code, I suggest continuing with pure DOM code:

 var closeSpan = document.createElement("span"); closeSpan.setAttribute("class","sr-only"); closeSpan.textContent = "Close"; 

In other words, just set the textContent value you want.

If you need compatibility with IE 8 or earlier, note that textContent does not exist for older browsers. For those older, you will have to use innerText (which works on IE 8 but is not part of any standard) or innerHTML . See the MDN page on textContent (referenced above) for a discussion of the differences between these fields.

+14
source

You can also try this.

 var closeSpan = document.createElement("span"); closeSpan.setAttribute("class","sr-only"); closeSpan.html("Close"); 
+1
source

Assuming you want to add a span tag to a div with id "myDiv":

 var span = $("span"); // create element span $(span).html("your text"); // add text $("#myDiv").append($(span)); // append it to the div element 
0
source

If you do not want to use jquery, you should use closeSpan.appendChild and document.createTextNode like this:

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

This method maximizes cross-browser compatibility. It will work in all browsers, including older versions of IE.

If you do want to use jquery, you can do it on one line:

 var closeSpan = $("<span></span>").addClass("sr-only").text("Close")[0]; 
0
source

Source: https://habr.com/ru/post/1205420/


All Articles