Insert HTML at Specified Positions3:39 with Guil Hernandez
InsertAdjacentHTML method to insert elements into the DOM. This method provides more control over inserting HTML inside a parent. You pass it the HTML and text content to create as a string, and then that string gets parsed and inserted into the DOM at the position you specify.
insertAdjacentHTML() accepts one of the following strings representing the position relative to an element:
'beforebegin': Before the
'afterbegin': Just inside the
element, before its first child.
'beforeend': Just inside the
element, after its last child.
'afterend': After the
Some additional thoughts:
It's worth mentioning that there are some security considerations that should be taken when inserting HTML into a page with
insertAdjacentHTML() and other similar methods.
Cross-site scripting (XSS) is a security exploit which allows an attacker to inject malicious client-side code into a website. This can occur when
insertAdjacentHTML() is used to insert plain text instead of raw text, which can then be executed as a script within the client's browser. For this reason, it is important to think about where the data is being inserted from. If data is being inserted from a trustworthy backend, then
insertAdjactentHTML() offers a fast an reliable approach to inserting content into the DOM.
To learn more, check out Treehouse's dedicated Web Security course. You may also want to read more in the security sections of these following MDN articles:
You need to sign up for Treehouse in order to download course files.Sign up