Answers for "add new element to html body using js"

5

add element to body javascript

var elem = document.createElement('div');
elem.style.cssText = 'position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000';
document.body.appendChild(elem);
Posted by: Guest on May-28-2020
1

How to add DOM elements to document body in javascript?

// The below code creates 3 paragraphs
// and adds them to document body

// 1. Create in-memory fragment to enhance performance
const fragment = document.createDocumentFragment();
const paragraphs = ["Paragraph1", "Paragraph2", "Paragraph3"];
// 2. Add paragraphs one by one to fragment
paragraphs.forEach((paragraph) => {
  const p = document.createElement("p");
  p.textContent = paragraph;
  fragment.appendChild(p);
});
// 3. Add resulting fragment to main DOM tree
document.body.appendChild(fragment);
Posted by: Guest on April-18-2022

Code answers related to "add new element to html body using js"

Code answers related to "Javascript"

Browse Popular Code Answers by Language