74

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?

Danny Beckett
  • 20,529
  • 24
  • 107
  • 134
Hello
  • 2,247
  • 4
  • 23
  • 29
  • 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 '13 at 03:28
  • Are you asking how to wrap the HTML into a few lines? – fardjad Apr 29 '13 at 03:28
  • 2
    Do you mean if the html string you want to insert is **very large** ? – gideon Apr 29 '13 at 03: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 '13 at 03:29
  • yes the string are to large – Hello Apr 29 '13 at 03:30
  • "the strings are too large" doesn't really say what the problem is. Please post a sample of the specific code you're having a problem with. – Geuis Apr 29 '13 at 03:31
  • possible duplicate of [JavaScript HERE-doc or other large-quoting mechanism?](http://stackoverflow.com/questions/2953682/javascript-here-doc-or-other-large-quoting-mechanism) – Danny Beckett Apr 30 '13 at 11:40
  • 8
    This question makes perfect sense and it's a really good question. Why the downvotes and the closing? – Keavon Aug 08 '13 at 18:00

9 Answers9

63

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>
Vadakkumpadath
  • 1,445
  • 13
  • 21
  • 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. – Eric Hepperle - CodeSlayer2010 Nov 27 '17 at 16:16
  • This best answer on here. – klewis Dec 08 '18 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 '19 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 '19 at 13:18
  • a hell lot of easier than the script tag approach (though the latter's still great), I mean, imagine the pain if you have like 1X HTML blocks – im_chc Jan 10 '19 at 16:17
  • you ma friend! will go far in life. Thanks! – Jey Miranda Jan 11 '19 at 23:22
  • 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 – dallin May 22 '19 at 17:57
  • how does the work out if there is a script tag in the string? I am having trouble with this. assume I cannot remove the script tag. – Bob9630 May 30 '19 at 02:27
  • Very useful. Thank you! – coterobarros Sep 30 '20 at 16:46
  • In 2023 VSCode was having none of it. It was NOT happy that I had a string split across two lines. However, you could (almost) do the same thing as long as you had a string followed by a +… not as pretty, but at least VSCode doesn’t complain. – Lloyd Sargent May 16 '23 at 16:12
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.

Danny Beckett
  • 20,529
  • 24
  • 107
  • 134
  • 1
    I like this. Kind of a pseudo-templating thing. – Geuis Apr 29 '13 at 03:31
  • Can I put variables in the template? – Hello Apr 29 '13 at 03: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 '13 at 03: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: https://developer.mozilla.org/en-US/docs/Web/API/Node/replaceChild – Joshua Fricke Nov 15 '18 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);
Geuis
  • 41,122
  • 56
  • 157
  • 219
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>";
Scott Jones
  • 2,880
  • 13
  • 19
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>
    `
ttfreeman
  • 5,076
  • 4
  • 26
  • 33
  • 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 '19 at 03: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);
venki
  • 1,121
  • 1
  • 9
  • 18
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

Community
  • 1
  • 1
ejntaylor
  • 1,900
  • 1
  • 25
  • 43
0

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

ANDROBETA
  • 11
  • 1
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(''); 
fruitloaf
  • 1,628
  • 15
  • 10