最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How can I append HTML code using JavaScript? - Stack Overflow

programmeradmin4浏览0评论

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?

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?

Share Improve this question edited Mar 17, 2020 at 12:48 Heretic Monkey 12.1k7 gold badges60 silver badges130 bronze badges asked Mar 17, 2020 at 12:46 Michal KMichal K 2432 gold badges3 silver badges10 bronze badges 8
  • 1 Please post your attempt. If you click edit and then [<>] snippet editor you can give us a minimal reproducible example – mplungjan Commented Mar 17, 2020 at 12:48
  • 1 What's the problem with .appendChild()? Build the <li> with all its child elements and then just append the <li> – Andreas Commented Mar 17, 2020 at 12:49
  • 2 But in the end this is still invalid markup. A <div> is not a valid child of a <span> – Andreas Commented Mar 17, 2020 at 12:50
  • why would you put a <div> into a <span>?? a span is an inline element, while a div is a block element. this is bad code – Iamnino Commented Mar 17, 2020 at 12:51
  • 1 div is perfectly valid child in a span, provided its CSS property display was set to inline. – Teemu Commented Mar 17, 2020 at 12:54
 |  Show 3 more comments

5 Answers 5

Reset to default 7

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>

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

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>

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>

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>

发布评论

评论列表(0)

  1. 暂无评论