0

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.

3
  • Can you show us what have you tried? Commented Oct 11, 2018 at 17:59
  • Kind of need to know if you're just transforming raw HTML, or if you're doing this in the context of the browser that is currently displaying that HTML, or if you're the server performing templating, or what. Commented Oct 11, 2018 at 18:02
  • Client side JS adding to an existing page. Commented Oct 11, 2018 at 18:02

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.