skip to Main Content

I have a set of ui and li structures. Currently, I have a requirement to concatenate the API to form 4 lis of data and put them behind the original li to add! I use the appendChild method, but you need to use this method first Create a node let div = document.createElement(‘div’); But this will cause the newly created label to add a div, which is a label I don’t want. I would like to ask if it is possible to create a virtual empty node and put li in it ? I don’t know how to do it specifically, and hope to get your help. I wrote an example such as the following case code to simulate my problem, thank you PS: I have tried to use innerHTML, but this will overwrite the original content when adding data in my actual project, so it does not work .

let str;
let wrap = document.querySelector('.wrap');
let div = document.createElement('div');
str += `<li>5555</li>
<li>6666</li>
<li>7777</li>
<li>8888</li>
`

div.innerHTML = str;
wrap.appendChild(div);
<ul class="wrap">
  <li>1111</li>
  <li>2222</li>
  <li>3333</li>
  <li>4444</li>
</ul>

2

Answers


  1. You added the jquery tag, so I am going to use it because it’s easier that way. With jQuery you can add multiple <li> tags at once, which is preferred because each DOM update is expensive.

    let html = `<li>5555</li>
    <li>6666</li>
    <li>7777</li>
    <li>8888</li>`;
    $('.wrap').append(html);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <ul class="wrap">
      <li>1111</li>
      <li>2222</li>
      <li>3333</li>
      <li>4444</li>
    </ul>
    Login or Signup to reply.
  2. Is it possible to create a virtual empty node and put <li> elements in it?

    Yes, this exactly what a DocumentFragment does. Once you append the fragment to the <ul>, the intermediate "virtual" node is skipped and its contents are transferred.

    However, a fragment does not have an .innerHTML property. For your use case, better use insertAdjacentHTML:

    const wrap = document.querySelector('.wrap');
    const str = `<li>5555</li>
    <li>6666</li>
    <li>7777</li>
    <li>8888</li>
    `;
    wrap.insertAdjacentHTML('beforeend', str);
    <ul class="wrap">
      <li>1111</li>
      <li>2222</li>
      <li>3333</li>
      <li>4444</li>
    </ul>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search