<!-- beforebegin -->
<p>
<!-- afterbegin -->
foo
<!-- beforeend -->
</p>
<!-- afterend -->Element: insertAdjacentHTML() method / notebook
Element: insertAdjacentHTML() method
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
<select id="position">
<option>beforebegin</option>
<option>afterbegin</option>
<option>beforeend</option>
<option>afterend</option>
</select>
<button id="insert">Insert HTML</button>
<button id="reset">Reset</button>
<p>
Some text, with a <code id="subject">code-formatted element</code> inside it.
</p>code {
color: red;
}if (typeof trustedTypes === "undefined")
trustedTypes = { createPolicy: (n, rules) => rules };const policy = trustedTypes.createPolicy("some-content-policy", {
createHTML(input) {
return input; // Do not do this in your own code!
// Instead do something like:
// return DOMPurify.sanitize(input);
},
});
const unsafeText = "<strong>inserted text</strong>";
const trustedHTML = policy.createHTML(unsafeText);const insert = document.querySelector("#insert");
insert.addEventListener("click", () => {
const subject = document.querySelector("#subject");
const positionSelect = document.querySelector("#position");
subject.insertAdjacentHTML(positionSelect.value, trustedHTML);
});
const reset = document.querySelector("#reset");
reset.addEventListener("click", () => {
document.location.reload();
});