Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating nested tags using document.createElement

I want to create a nested tag using javascript createElement function like

<li><span class="toggle">Jan</span></li>

Can anyone give me an idea how to do it?

like image 457
my name is xyz Avatar asked Aug 07 '12 07:08

my name is xyz


People also ask

What is nested tag with example?

It is often necessary to code certain tags (and their text) within the definition of other tags (between the start and end tags). This is called nesting. A good example of nesting is the relationship between the DL (definition list) tag, the DT (definition term) tag, and the DD (definition description) tag.

What is document createElement (' a ')?

createElement() In an HTML document, the document. createElement() method creates the HTML element specified by tagName, or an HTMLUnknownElement if tagName isn't recognized.

Can tags be nested?

Nesting tags can take on many different forms and can be complex. For example, some tags allow multiple tags or multiple occurrences of the same tag to be nested, while other tags do not allow nesting of any tags. You can also nest levels of certain tags, that is, nested tags within other nested tags.


2 Answers

The simplest way is with createElement() and then set its innerHTML:

var tag = document.createElement("li");
tag.innerHTML = '<span class="toggle">Jan</span>';

You can then add it to the document with .appendChild() wherever you want it to go.

like image 83
jfriend00 Avatar answered Oct 05 '22 22:10

jfriend00


var li = document.createElement('li');
var span = document.createElement('span');
span.className = 'toggle';
span.appendChild(document.createTextNode('Jan'));
li.appendChild(span);
like image 39
Vatev Avatar answered Oct 06 '22 00:10

Vatev