Home  »  CheatsheetsCodeProgrammingSnippetsSoftwareTechnology   »   JavaScript add Element to the Dom

JavaScript add Element to the Dom

Posted: March 10, 2022 | by Michael Bright

JavaScript add element to the Dom code.

// create a temporary dom element
var temp = document.createElement('div'); 

// Add content to div
temp.innerHTML = '<p>some html string</p>'; 

//select the element to append to
var element = document.getElementById("myElementID");
element.appendChild(temp);

//alternate
var element = document.querySelector('#some-element');
element.appendChild(temp);

Found this article interesting? Follow Brightwhiz on Facebook, Twitter, and YouTube to read and watch more content we post.