I want to create some html via JS, therefore I need to write the html inside the JS file like:
function createHtmlSection() {
return "<li class=\"chapter up-wrapper-btn\">" +
"<div>" +
"<button><i class=\"fa fa-plus\" onclick=\"addSection('up',this)\"></i></button>" +
"<label contenteditable=\"true\">section 1</label>" +
"</div>" +
"</li>";
}
is there a tool or some shortcut to create this type of html string?
I mean, in this case I was needed to type all this html by hand. with +
and needed to add "
sign.
Something that can convert this:
<li class="chapter up-wrapper-btn">
<div>
<button><i class="fa fa-plus" onclick="addSection('up',this)"></i></button>
<label contenteditable="true">section 1</label>
</div>
</li>
to the first string that I was needed to type by hand
parseHTML uses native methods to convert the string to a set of DOM nodes, which can then be inserted into the document. These methods do render all trailing or leading text (even if that's just whitespace).
Just call the method html2text with passing the html text and it will return plain text.
You can use a template literal (note the back-ticks). The literal supports multiline, and you won't need to escape the quotes (you'll need to escape back-ticks).
`<li class="chapter up-wrapper-btn">
<div>
<button><i class="fa fa-plus" onclick="addSection('up',this)"></i></button>
<label contenteditable="true">section 1</label>
</div>
</li>`
Example:
function createHtmlSection() {
return `
<li class="chapter up-wrapper-btn">
<div>
<button><i class="fa fa-plus" onclick="addSection('up',this)"></i></button>
<label contenteditable="true">section 1</label>
</div>
</li>
`;
}
document.querySelector('#root')
.innerHTML = createHtmlSection();
<ul id="root"></ul>
You can also pass parameters to the function, and insert them to the string using expression interpolation:
function createHtmlSection(label) {
return `
<li class="chapter up-wrapper-btn">
<div>
<button><i class="fa fa-plus" onclick="addSection('up',this)"></i></button>
<label contenteditable="true">${label}</label>
</div>
</li>
`;
}
document.querySelector('#root')
.innerHTML = createHtmlSection('!!! section !!!');
<ul id="root"></ul>
update your JS file to:
function createHtmlSection() {
return `
<li class="chapter up-wrapper-btn">
<div>
<button>
<i class="fa fa-plus" onclick="addSection('up',this)"></i>
</button>
<label contenteditable="true">section 1</label>
</div>
</li>
`
}
Read this link for more information: template literals
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With