Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
Use the 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.
Further Reading
Position arguments
insertAdjacentHTML()
accepts one of the following strings representing the position relative to an element:
-
'beforebegin'
: Before theelement
itself. -
'afterbegin'
: Just inside theelement
, before its first child. -
'beforeend'
: Just inside theelement
, after its last child. -
'afterend'
: After theelement
itself.
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 that 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 and reliable approach to inserting content into the DOM.
If your data source is unknown, you may want to consider using Node.textContent or Element.insertAdjacentText(), as these will insert the content as raw text instead of HTML.
To learn more, check out Treehouse's dedicated Web Security course. You may also want to read more in the security sections of the following MDN articles:
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up