Charles Saag
Charles Saag

Reputation: 631

What is proper method of appending multiple lines of HTML using JavaScript?

I'm aware of appendChild and createElement but these are methods to use when I'm adding a single line of HTML. I recognize I could add a script object, or an iframe object using this approach, but how would I in JavaScript add 20+ lines of HTML to an existing HTML document?

I built a search.js file to address searching requirements of an HTML page. It works great! But I want to encapsulate my search form and CSS and was thinking I could append the data to an existing HTML document to keep things compact and more manageable.

UPDATE: So the JavaScript would be added to an existing HTML page at the bottom within two SCRIPT tags. The JS would append a string - which would be 20+ lines of HTML stringified - to an existing page, which I had hoped would render as HTML.

var sectionAsHtml = '' +
'<div class='xyz'>' +
' <div class='abc'>' +
'  <p>This is just an example for demonstration purposes.</p>' +
' </div>' +
'</div>';

I would then locate the body of my HTML using a ".getElementById" find, and then ".appendChild" the above string.

Upvotes: 0

Views: 950

Answers (1)

connexo
connexo

Reputation: 56754

You can use the function createElement() like below:

let html = `<ul>
  <li>Li 1</li>
  <li>Li 2</li>
</ul>
<div id="test">Testdiv</div>`

function createElement( str ) {
    var frag = document.createDocumentFragment();

    var elem = document.createElement('div');
    elem.innerHTML = str;

    while (elem.childNodes[0]) {
        frag.appendChild(elem.childNodes[0]);
    }
    return frag;
}

let fragment = createElement(html)
document.getElementById('app').appendChild(fragment)
<div id="app">
  <h1>The App</h1>
</div>

Taken from this answer to a similar problem: https://stackoverflow.com/a/3662980/3744304

Upvotes: 2

Related Questions