How to Store HTML Code in Javascript Variable - Cyber Tweaks

Ads Top

How to Store HTML Code in Javascript Variable

Storing HTML Code Block to a JavaScript Variable DOM

Variable refers to something that can change. Variables in JavaScript retain the data value and may be modified at any moment.

JavaScript uses the reserved keyword 'var' to declare a variable. A variable must have a unique name.

The simplest and safest approach to assign or store a block of HTML code in a JavaScript variable using the concatenation operator (+).

When stringifying the HTML code block, use single quotes to make it simpler to maintain the double quotes in the real HTML code.

You must also escape the single quotes that exist within the text of an HTML block — just replace the ' character with \', as shown in the example below


<div id="content"></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("content").innerHTML = codeBlock
</script>

You can add prefix ' postfix ' + to each line of HTML Code to put it within Javascript.

Alternatively Your Can Use Tool HTML or Text to Javascript or Java variable Converter

Use the code to display content from the stored html code <div id="content"></div>

This script can be useful to hide big HTML code within javascript and display content separately using DIV

No comments:

Powered by Blogger.