2

How to assign block of HTML code to a JavaScript variable

 2 years ago
source link: https://www.laravelcode.com/post/how-to-assign-block-of-html-code-to-a-javascript-variable
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Ad byValueimpression

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.

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>



About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK