Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I'm trying to write text into an element span with function .text(), but I got this error UncaughtTypeError: undefined is not a function, and I also tried function append(), innerHtml(), createTextNode() with no success.

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 
like image 559
Joe Avatar asked Oct 24 '14 06:10

Joe


People also ask

How do I add text to span?

If you need to append or prepend text to the existing content of the span element, use the insertAdjacentText method instead. Copied! const span = document. getElementById('span'); // ✅ Append / Prepend text to the span span.

Does span have textContent?

Use the textContent property to get the text of a span element, e.g. const text = span. textContent . The textContent property will return the text content of the span and its descendants. If the element is empty, an empty string is returned.


1 Answers

Since you are starting with pure DOM code, I'd suggest continuing with pure DOM code:

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

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

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

like image 95
Louis Avatar answered Nov 01 '22 17:11

Louis