Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
136
rated 0 times [  141] [ 5]  / answers: 1 / hits: 12312  / 4 Years ago, tue, march 17, 2020, 12:00:00

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?


More From » html

 Answers
0

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);




[#4468] Friday, March 13, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ravenl

Total Points: 338
Total Questions: 107
Total Answers: 112

Location: Belize
Member since Mon, Jun 20, 2022
2 Years ago
ravenl questions
Thu, Feb 18, 21, 00:00, 3 Years ago
Tue, Jan 12, 21, 00:00, 3 Years ago
Tue, Dec 3, 19, 00:00, 5 Years ago
;