In this JavaScript tutorial we learn about how we use JavaScript Append HTML to Body. There are two ways or JavaScript method which we use to append HTML element to the HTML body.
- Using innerHTML attribute, innerHTML is the HTML DOM property.
- Using insertAdjacentHTML() DOM function.
Using innerHTML DOM property
Introduction to innerHTML Attribute
InnerHTML attribute is the DOM (Document Object Model) property. It is used for setting the HTML content to the element.
Below is the example of how we use innerHTML on our code,
Syntax:
HTMLElementObject.innerHTML = text
Append HTML to Body Using innerHTML
See the Pen
Append HTML to Body Using innerHTML by Bikash Panda (@phpcodertech)
on CodePen.
Note: This method basically removes all the content from the div and recreate the new div with new content. So if you have any child node they will also remove.
Using insertAdjacentHTML() DOM function
Introduction to insertAdjacentHTML() DOM function
insertAdjacentHTML()
DOM function is used for insert div content or any HTML content on the following mentioned position,
- “afterbegin”
- “afterend”
- “beforebegin”
- “beforeend”
Syntax:
node.insertAdjacentHTML(position, text)
Append HTML to Body Using innerHTML
See the Pen Example of insertAdjacentHTML() DOM function by Bikash Panda (@phpcodertech) on CodePen.
https://static.codepen.io/assets/embed/ei.jsHere is a complete reference about how we append HTML element inside or any predefined position on the div
element.
Conclusion
On the above tutorial we use 2 method to append HTML element using JavaScript DOM methods,
- Using
innerHTML
Syntax:HTMLElementObject.innerHTML = text
- Using
insertAdjacentHTML
Syntax:node.insertAdjacentHTML(position, text)
This is a complete solution where we check JavaScript append functionality with live example.
If you have facing issue please comment below.
Also Check:
- Send Mail Attachments with PHP Mail()
- Selection in CSS | CSS ::selection
- How to Integrate Google Translate on website
Happy Coding..!
Nice Post