Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a span element inside another element using javascript

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)); 
like image 755
Nicekiwi Avatar asked Apr 27 '11 10:04

Nicekiwi


People also ask

Can you use span in JavaScript?

You can use the HTML span tag as a container to group inline elements together so you can style or manipulate them with JavaScript.

Is it possible to put a div within span?

As all phrasing content is flow content, it means phrasing element can be used in all of flow content. The phrasing elements can only contain other phrasing elements, for example, you can't put div inside span.

Can we add span in a tag?

The span tag is used for the grouping of inline elements & this tag does not make any visual change by itself. span is very similar to the div tag, but div is a block-level tag and span is an inline tag. Example 1: In this example, we simply use span tag with style in HTML.


1 Answers

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); 
like image 66
Naren Sisodiya Avatar answered Oct 14 '22 23:10

Naren Sisodiya