75

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?

8
  • 2
    I'm afraid I don't understand the question. What is "a block html"? Perhaps you can represent your problem code by adding it to the question.
    – Geuis
    Apr 29, 2013 at 3:28
  • Are you asking how to wrap the HTML into a few lines?
    – fardjad
    Apr 29, 2013 at 3:28
  • 2
    Do you mean if the html string you want to insert is very large ?
    – gideon
    Apr 29, 2013 at 3:29
  • 1
    What you're doing seems just fine? Is there a problem, or something that does not work with that approach, and how much is "large html" in bytes exactly ?
    – adeneo
    Apr 29, 2013 at 3:29
  • 8
    This question makes perfect sense and it's a really good question. Why the downvotes and the closing?
    – Keavon
    Aug 8, 2013 at 18:00

9 Answers 9

64

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 = `
    <div class="parent">
        <div class="child">${a}</div>
        <div class="child">+</div>
        <div class="child">${b}</div>
        <div class="child">=</div>
        <div class="child">${a + b}</div>
    </div>
`;
document.getElementById('posts').appendChild(div);
.parent {
  background-color: blue;
  display: flex;
  justify-content: center;
}
.post div {
  color: white;
  font-size: 2.5em;
  padding: 20px;
}
<div id="posts"></div>

10
  • Thanks! The template literals worked for me in Chrome 63.0.3239.59 (Official Build) beta (64-bit). Perl has had this type of feature for many years already, so I was somewhat familiar, though I didn't know the technical term in JavaScript. I'm injecting css styles in a script tag into my page that I'm building dynamically. Nov 27, 2017 at 16:16
  • This best answer on here.
    – klewis
    Dec 8, 2018 at 12:56
  • @klewis not convinced. Visual Studio explodes with syntax error if you try this, even if the browser handles it well.
    – egmfrs
    Jan 10, 2019 at 11:46
  • @gmfrs I experienced the same thing you are talking about, but was then advised that the cause maybe because of lack of ES6 support that is provided while compiling code. With the realization, its all good from here.
    – klewis
    Jan 10, 2019 at 13:18
  • 3
    Be aware that template literals do not have support in any version of Internet Explorer (even version 11), but they are supported in MS Edge. They also aren't supported by Opera Mini, IE Mobile, and Blackberry Browser. If you need to support these browsers, you should probably use the <script> tag approach described above by Danny Beckett.
    – dallin
    May 22, 2019 at 17:57
57

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:

// Create a temporary <div> to load into
var div = document.createElement('div');
div.setAttribute('class', 'someClass');
div.innerHTML = document.getElementById('blockOfStuff').innerHTML;

// You could optionally even do a little bit of string templating
div.innerHTML = div.innerHTML
    .replace(/{VENDOR}/g, 'ACME Inc.')
    .replace(/{PRODUCT}/g, 'Best TNT')
    .replace(/{PRICE}/g, '$1.49');

// Write the <div> to the HTML container
document.getElementById('targetElement').appendChild(div);
.red {
    color: red
}
<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."<br><br>
    <b>Vendor:</b> {VENDOR}<br>
    <b>Product:</b> {PRODUCT}<br>
    <b>Price:</b> {PRICE}
</script>

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

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 whitespace before them!


Why use Nowdoc in PHP?

One huge advantage of using Nowdoc syntax over the usual starting and stopping your PHP tag is its support for variables. Consider the normal way of doing it - shown in the example below:

<?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>

Contrast that to the simplicity of Nowdoc.

4
  • 1
    I like this. Kind of a pseudo-templating thing.
    – Geuis
    Apr 29, 2013 at 3:31
  • Can I put variables in the template?
    – Hello
    Apr 29, 2013 at 3:31
  • 1
    I'll upvote this for being a proper abomination and not something most developers would ever consider doing, even if it does work.
    – adeneo
    Apr 29, 2013 at 3:41
  • You could also get creative with replaceChild() if you didn't want the node to exist which is simply a placeholder for where you eventually want the content. See this for inspiration: developer.mozilla.org/en-US/docs/Web/API/Node/replaceChild Nov 15, 2018 at 23:21
22

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);
0
15

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>";
1
  • 1
    Great and simple solution.
    – Armin
    May 28, 2019 at 22:32
3

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>
    `
1
  • 2
    A duplicate answer. Two years later and offers nothing new. The original answer has better example, is more descriptive and is calling backtick string by its real name:Template literals.
    – papo
    Dec 16, 2019 at 3:06
2

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);
0
0

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

0

By far the easiest way is to use the insertAdjacentHTML() method. w3schools article

0

Just make sure to wrap you LARGE CODE INTO A SINGLE DIV like a wrapper, then it doesn't matter how long it is.

HTML:

<div id='test'></div>

JS:

const arr = ['one', 'two', 'three'];

let mapped = arr.map(value=> {
  return `
    <div>
    <hr />
    <h1>${value}</h1>
    <h3>this is it</h3>
    </div>
  `
});

document.querySelector('#test').innerHTML = mapped.join(''); 
1
  • almost feels like react.js
    – klewis
    Feb 23 at 18:34

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.