Joe
Joe

Reputation: 7919

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

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

Upvotes: 27

Views: 55887

Answers (4)

Sean
Sean

Reputation: 4515

If you don't want to use jquery, you would use closeSpan.appendChild and document.createTextNode like so:

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 old versions of IE.

If you do want to use jquery, you could do this in one line:

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

Upvotes: 7

Louis
Louis

Reputation: 151380

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.

Upvotes: 54

anusha
anusha

Reputation: 2135

You can try this also

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

Upvotes: -1

Joe
Joe

Reputation: 353

Assuming you want to add the "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

Upvotes: -1

Related Questions