How do convert HTML into a line and add it to an element?
-
Hello. Please. There's a line:
var mainContainer = document.getElementById('main'); var containerHTML = "<div class='test'>Hello</div>";
I want to add this line to another element as a line, not as a html element.
function addStr(str) { var mainContainer = document.getElementById('main'); mainContainer.insertAdjacentHTML('afterBegin', str); } addStr(containerHTML);
But this operation adds a line like HTML, so I only see hello. How about we do that?
html = html.replace(/</g, '<'); html = html.replace(/>/g, '>');
-
You can take advantage of your properties. https://developer.mozilla.org/ru/docs/Web/API/Node/textContent
document.getElementById('d').textContent += "<div class='test'>Hello</div>"; document.getElementById('d').textContent += "<div class='test'>Hello</div>";
<div id='d'></div>
Alternatively, before adding, just screen html symbols
function htmlEscape(str) { return String(str) .replace(/&/g, '&') .replace(/"/g, '"') .replace(/'/g, ''') .replace(/</g, '<') .replace(/>/g, '>'); }
function addStr(str) {
var mainContainer = document.getElementById('d');
mainContainer.insertAdjacentHTML('afterBegin', htmlEscape(str));
}
addStr("<div class='test'>Hello</div>");
addStr("<div class='test'>Hello</div>");<div id='d'></div>