How to insert a large block of HTML in JavaScript?

后端 未结 7 875
悲哀的现实
悲哀的现实 2020-12-07 18:50

If I have a block of HTML with many tags, how do insert it in JavaScript?

var div = document.createElement(\'div\');
div.setAttribute(\'class\', \'post block         


        
7条回答
  •  余生分开走
    2020-12-07 19:01

    Template literals may solve your issue as it will allow writing multi-line strings and string interpolation features. You can use variables or expression inside string (as given below). It's easy to insert bulk html in a reader friendly way.

    I have modified the example given in question and please see it below. I am not sure how much browser compatible Template literals are. Please read about Template literals here.

    var a = 1, b = 2;
    var div = document.createElement('div');
    div.setAttribute('class', 'post block bc2');
    div.innerHTML = `
        
    ${a}
    +
    ${b}
    =
    ${a + b}
    `; document.getElementById('posts').appendChild(div);
    .parent {
      background-color: blue;
      display: flex;
      justify-content: center;
    }
    .post div {
      color: white;
      font-size: 2.5em;
      padding: 20px;
    }

提交回复
热议问题