Suppose the following example:
let html = `<Parent customAttr={ value }>
<Child className="container" />
</Parent>`;
let div = document.createElement('div');
div.innerHTML = html;
// or
div.insertAdjacentHTML('beforeend', html);
console.log(div);
When inserting the html
variable as innerHTML
of the div
, first letters of <Parent>
and <Child>
elements become lowercased, camelCase of the attributes are lost and { value }
becomes wrapped into double quotes.
Is it possible and how to keep everything without these changes when inserting as innerHTML
?
CodePudding user response:
from mdn web docs :
What exactly happens when you set value of innerHTML? Doing so causes the user agent to follow these steps:
The specified value is parsed as HTML or XML (based on the document type), resulting in a DocumentFragment object representing the new set of DOM nodes for the new elements. If the element whose contents are being replaced is a element, then the element's content attribute is replaced with the new DocumentFragment created in step 1. For all other elements, the element's contents are replaced with the nodes in the new DocumentFragment.
so you can't do what you want with innerHtml
CodePudding user response:
You can simply add content to the element.
div.innerHTML = html