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?
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?
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.
clone()
function instead createElement()
for every li
element.
clone()
? What advantage does that have over createElement()
for this purpose?
Commented
Aug 7, 2012 at 7:24
cloneNode()
should has some advantages for memory issues instead creating for every time a new element. In this way, you just referring the tag
(which is created first) element and no more mem allocation with creating new elements. var li=createElement("li"), l; l=li.cloneNode(true); l.innerHTML="..."; l.cloneNode(true); l.innerHTML="..."; so on...
cloneNode()
using less memory. Do you have a reference on that?
Commented
Aug 7, 2012 at 7:44
var li=document.createElement("li");
Now, I have one var
at memory and not pushing-stuffing var
s anymore to memory, but just referring to it when I need same thing writing l=li.cloneNode(true)
and also overwriting on l
every time. I think this must be useful and has advantages. Or writing like this? var li; li=document.createElement("li"); do someth... li=document.createElement("li"); do s...; li=document.createElement("li"); ...
var li = document.createElement('li');
var span = document.createElement('span');
span.className = 'toggle';
span.appendChild(document.createTextNode('Jan'));
li.appendChild(span);
I have written a function that is suitable for use when we want to convert an nested JSON to html tags.You can change it according to your needs or event convert it to JQuery. I use this to convert a JSON response to html.
let createContentByJson = function (target, obj) {
const el = document.createElement(obj.tag);
if (obj.hasOwnProperty('class'))
el.classList.add(obj.class);
if (obj.hasOwnProperty('text'))
el.textContent = obj.text;
if (obj.hasOwnProperty('id'))
el.id = obj.id;
target.append(el);
if (obj.hasOwnProperty('inner'))
obj.inner.forEach((inner_el) => {
createContentByJson(el, inner_el);
});
};
createContentByJson(document.querySelector('#target'),{
tag: 'div',
class: 'parent-div',
id: 'parent',
inner:[
{
tag: 'p',
class: 'child-class1',
text: 'child1'
},
{
tag: 'p',
class: 'child-class2',
text: 'chid2'
}
]
});
<div id="target"></div>