Reputation: 243
I'm trying to add an element to the DOM using JavaScript. I have a ul
and I want to add a li
. Its nothing difficult using appendChild
but I want my li
to be more complicated.
This is the output that I'm trying to achieve:
<li>
<span class="author">Me</span>
<span class="message">Message...</span>
<span class="time">
<div class="line"></div>
15:21
</span>
</li>
let author = "me";
let message = "Message...";
let time = "15:21";
As you can see what I'm trying to achieve isn't just a basic li
with some text (innerHTML) but quite a big chunk of HTML code.
My question is how I can achieve to get this output using JavaScript. Or should I use some JavaScript library or something to make it easier?
Upvotes: 4
Views: 20649
Reputation: 24181
Here is a little trick you can use.
You can actually use existing DOM (HTML) as a kind of template, basically clone the element and then replace the parts with the values you want.
First you remove the Element from the DOM with the remove, although the element has be removed from the DOM, it doesn't stop you from cloning it.
Now whenever you want another one, call clone(true)
, true = deepClone, and the using querySelector replace parts of the DOM with the bits you want. Finally add this cloned element to the DOM.
Below is a simple example..
const ol = document.querySelector('ol');
const template = document.querySelector('li');
template.remove();
function append(o) {
const {author, message, time} = o;
const clone = template.cloneNode(true);
clone.querySelector('.author').innerText=author;
clone.querySelector('.message').innerText=message;
clone.querySelector('.time').lastChild.nodeValue=time;
ol.appendChild(clone);
}
append({
author: "me",
message: "Message...",
time: "15:21"
});
append({
author: "Another me",
message: "Something else..",
time: "12:42"
});
append({
author: "Whatever",
message: "lalala..",
time: "17:20"
});
.author {
font-weight: bold;
margin-right: 1rem;
}
.time {
color: green;
}
li {
margin: 0.5rem;
border: 1px solid silver;
}
.line {
border-bottom: 1px dotted red;
}
<ol>
<li>
<span class="author">Me</span>
<span class="message">Message...</span>
<span class="time">
<div class="line"></div>
15:21
</span>
</li>
</ol>
Upvotes: 0
Reputation: 22265
the more simple, (for me)
const DomParser = new DOMParser()
function makeLI( author, message, time)
{
let ElemLI =
`<li>
<span class="author">${author}</span>
<span class="message">${message}</span>
<span class="time">
<div class="line"></div>
${time}
</span>
</li>`
return (DomParser.parseFromString( ElemLI, 'text/html')).body.firstChild
}
// proof...
myList.appendChild(makeLI('you','Message...','15:21'))
myList.appendChild(makeLI('me','someone in ?','21:25'))
<ul id="myList"></ul>
Upvotes: 0
Reputation: 63524
You can use a template literal and insertAdjacentHTML
for a clean approach.
function createListItem({ author, message, time }) {
return `<li>
<span class="author">${author}</span>
<span class="message">${message}</span>
<span class="time">
<div class="line"></div>
${time}
</span>
</li>`;
}
const ul = document.querySelector('ul');
ul.insertAdjacentHTML('beforeend', createListItem({
author: 'me',
message: 'Message...',
time: '15:21'
}));
.line { display: inline };
<ul>
<li>Current</li>
</ul>
Upvotes: 4
Reputation: 1752
If you want to insert html elements string as html node, you have to create html elements to use with appendChild()
However insertAdjacentHTML()
allows you to add html elements if passed as string.
https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
let author = "me";
let message = "Message...";
let time = "15:21";
let str = `<li><span class="author">${author}</span><span class="message">${message}</span><span class="time"><div class="line"></div>${time}</span></li>`;
document.querySelector('#nav').insertAdjacentHTML('beforeend', str);
<ul id='nav'><ul>
let html = `<li>
<span class="author">Me</span>
<span class="message">Message...</span>
<span class="time">
<div class="line"></div>
15:21
</span>
</li>`;
document.querySelector('#list').insertAdjacentHTML('beforeend', html);
<ul id='list'></ul>
Upvotes: 7
Reputation: 2271
Take a look at this original link for that code where we append to the DOM. Then you can use string interpolation to add the variables to the code like below
function appendHtml(el, str) {
var div = document.createElement('div'); //container to append to
div.innerHTML = str;
while (div.children.length > 0) {
el.appendChild(div.children[0]);
}
}
let author = "me";
let message = "Message...";
let time = "15:21";
var html = `<li><span class="author">${author}</span><span class="message">${message}</span><span class="time"><div class="line"></div>${time}</span></li>`;
appendHtml(document.body, html);
Upvotes: 6