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
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With