[javascript] How to insert a large block of HTML in JavaScript?

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 bc2');
div.innerHTML = 'HERE TOO MUCH HTML that is much more than one line of code';
document.getElementById('posts').appendChild(div);

How do I do it right?

This question is related to javascript html

The answer is


If I understand correctly, you're looking for a multi-line representation, for readability? You want something like a here-string in other languages. Javascript can come close with this:

var x =
    "<div> \
    <span> \
    <p> \
    some text \
    </p> \
    </div>";

Add each line of the code to a variable and then write the variable to your inner HTML. See below:

var div = document.createElement('div');
div.setAttribute('class', 'post block bc2');
var str = "First Line";
str += "Second Line";
str += "So on, all of your lines";
div.innerHTML = str;
document.getElementById('posts').appendChild(div);

Despite the imprecise nature of the question, here's my interpretive answer.

var html = [
    '<div> A line</div>',
    '<div> Add more lines</div>',
    '<div> To the array as you need.</div>'
].join('');

var div = document.createElement('div');
    div.setAttribute('class', 'post block bc2');
    div.innerHTML = html;
    document.getElementById('posts').appendChild(div);

The easiest way to insert html blocks is to use template strings (backticks). It will also allow you to insert dynamic content via ${...}:

document.getElementById("log-menu").innerHTML = `
            <a href="#"> 
               ${data.user.email}
            </a>
            <div class="dropdown-menu p-3 dropdown-menu-right">
                <div class="form-group">
                    <label for="email1">Logged in as:</label>
                    <p>${data.user.email}</p>
                </div>
                <button onClick="getLogout()" ">Sign out</button>
            </div>
    `

This answer does not use backticks/template literals/template strings (``), which are not supported by Internet Explorer.

Using HTML + JavaScript:

You could keep the HTML block in an invisible container (like a <script>) within your HTML code, then use its innerHTML at runtime in JS

For example:

_x000D_
_x000D_
var div = document.createElement('div');
div.setAttribute('class', 'someClass');
div.innerHTML = document.getElementById('blockOfStuff').innerHTML;
document.getElementById('targetElement').appendChild(div);
_x000D_
.red {
    color: red
}
_x000D_
<script id="blockOfStuff" type="text/html">
    Here's some random text.
    <h1>Including HTML markup</h1>
    And quotes too, or as one man said, "These are quotes, but
    'these' are quotes too."
</script>

<div id="targetElement" class="red"></div>
_x000D_
_x000D_
_x000D_

Idea from this answer: JavaScript HERE-doc or other large-quoting mechanism?

Using PHP:

If you want to insert a particularly long block of HTML in PHP you can use the Nowdoc syntax, like so:

<?php

    $some_var = " - <b>isn't that awesome!</b>";

    echo
<<<EOT
    Here's some random text.
    <h1>Including HTML markup</h1>
    And quotes too, or as one man said, "These are quotes, but 'these' are quotes too."
    <br><br>
    The beauty of Nowdoc in PHP is that you can use variables too $some_var
    <br><br>
    Or even a value contained within an array - be it an array from a variable you've set
    yourself, or one of PHP's built-in arrays. E.g. a user's IP: {$_SERVER['REMOTE_ADDR']}
EOT;

?>

Here's a PHP Fiddle demo of the above code that you can run in your browser.

One important thing to note: The <<<EOT and EOT; MUST be on their own line, without any preceding whitespace.


One huge advantage of using Nowdoc syntax over the usual starting and stopping your PHP tag is its support for variables. Consider the usual way of doing it (shown in the example below), contrasted to the simplicity of Nowdoc (shown in the example above).

<?php

    // Load of PHP code here

?>

Now here's some HTML...<br><br>

Let's pretend that this HTML block is actually a couple of hundred lines long, and we
need to insert loads of variables<br><br>

Hi <?php echo $first_name; ?>!<br><br>

I can see it's your birthday on <?php echo $birthday; ?>, what are you hoping to get?

<?php

    // Another big block of PHP here

?>

And some more HTML!
</body>
</html>

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.

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


If you are using on the same domain then you can create a seperate HTML file and then import this using the code from this answer by @Stano :

https://stackoverflow.com/a/34579496/2468603