(+)
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.
You also need to escape the single-quotes which appears inside the content of HTML block — just replace the '
character with \'
, as shown in the following example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Store HTML Code in JavaScript Variable</title>
</head>
<body>
<div id="wrapper"></div>
<script>
// Storing HTML code block in a variable
var codeBlock = '<div class="content">' +
'<h1>This is a heading</h1>' +
'<p>This is a paragraph of text.</p>' +
'<p><strong>Note:</strong> If you don\'t escape "quotes" properly, it will not work.</p>' +
'</div>';
// Inserting the code block to wrapper element
document.getElementById("wrapper").innerHTML = codeBlock
</script>
</body>
</html>
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on harsukh21@gmail.com
How to Split a String into an Array of Characters in JavaScript
Use the split() Method The JavaScript...How to Get the data-id Attribute of an Element Using jQuery
Use the jQuery attr() Method You can...How to Set the Value of Input Text Box using jQuery
Use the jQuery val() Method You can s...How to get original image size (width & height) in JavaScript
Use the HTML5 naturalWidth and...How to create a string by joining the values of an array in PHP
Use the PHP implode() or ...