Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 950
Hello Avatar asked Apr 29 '13 03:04

Hello


People also ask

How do you assign a block of HTML to a JavaScript variable?

Answer: Use the concatenation operator (+) The simple and safest way to use the concatenation operator ( + ) to assign or store a bock of HTML code in a JavaScript variable. You should use the single-quotes while stingify the HTML code block, it would make easier to preserve the double-quotes in the actual HTML code.

How do you embed HTML into JavaScript?

You can add JavaScript code in an HTML document by employing the dedicated HTML tag <script> that wraps around JavaScript code. The <script> tag can be placed in the <head> section of your HTML or in the <body> section, depending on when you want the JavaScript to load.

How do you add a block in HTML?

Click on the Actions menu on the right-hand side of the HTML block. Select Configure (new HTML block) block. Give the block a name using the Block title field. Click on </> to switch to the HTML view in order to add HTML code.

Can I use HTML tags in JavaScript?

JavaScript is a scripting language, not a HTMLanguage type. It is mainly to do process at background and it needs document. write to display things on browser.


2 Answers

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.

like image 166
Danny Beckett Avatar answered Sep 21 '22 07:09

Danny Beckett


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>
like image 30
Vadakkumpadath Avatar answered Sep 21 '22 07:09

Vadakkumpadath