Create a span element inside another element using javascript

Nicekiwi picture Nicekiwi · Apr 27, 2011 · Viewed 74.6k times · Source

This code is from google calender.

var dateString =  (startJSDate.getMonth() + 1) + "/" + startJSDate.getDate();
  if (!startDateTime.isDateOnly()) {
  dateString += " @ " + startJSDate.getHours() + ":" + 
  padNumber(startJSDate.getMinutes());
}
 dateString = "<span>" +dateString + "</span>";
 var li = document.createElement('li');

I need to add a span tag around the variable dateString, adding them as above returns "1234" as text on the page.

The string is rendered as such:

li.appendChild(document.createTextNode(' - ' + dateString));

Answer

Naren Sisodiya picture Naren Sisodiya · Apr 27, 2011

Try following code, create span using createElement and insert date string in it as innerHTML. Then append span to li.

var dateSpan = document.createElement('span')
dateSpan.innerHTML = dateString;
var li = document.createElement('li');
li.appendChild(dateSpan);