Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically creating HTML elements using Javascript?

Tags:

I want to dynamically create some HTML elements (3 html element) and then return this html code as a string in a variable. I don't want to write the HTML code in the following function to some div, but, I want to return it in a var.

function createMyElements(id1,id2,id3){     //create anchor with id1    //create div with id 2    //create xyz with id3    //now return the html code of above created just now  } 

How can I do this?

like image 826
dojoX Avatar asked Apr 04 '11 09:04

dojoX


People also ask

Can HTML elements be created dynamically by JavaScript?

New elements can be dynamically created in JavaScript with the help of createElement() method. The attributes of the created element can be set using the setAttribute() method.

How JavaScript can create dynamic HTML content?

DHTML included JavaScript along with HTML and CSS to make the page dynamic. This combo made the web pages dynamic and eliminated this problem of creating static page for each user. To integrate JavaScript into HTML, a Document Object Model(DOM) is made for the HTML document.

Can JavaScript create HTML elements?

Mostly, for simplicity, developers define and create elements inside HTML. However, it is not the only way to create elements and we can also create elements using the JavaScript document object method createElement() to make our webpage more dynamic. Due to the document object, we can access HTML elements.


2 Answers

[Edit 2021/10] This answer is now > 10 years old. Here is a snippet containing several ways to create and/or inject elements. The answer for the question asked (create some element(s) and retrieve their html code) can be found @ the bottom of the snippet.

// The classic createElement // ------------------------- // create a paragraph element using document.createElement const elem = document.createElement(`p`); elem.id = `myBrandnewDiv1`;  // put in some text elem.appendChild(document.createTextNode(`My brand new div #1`));  // append some html (for demo, preferrably don't use innerHTML) elem.innerHTML += ` =&gt; created using    <code>document.createElement</code>`;  // append a new paragraph within #myBrandNewDiv1 const nested = elem.appendChild(document.createElement(`p`)); nested.classList.add(`nested`); // add some text to that nested.textContent = `I am nested!`; // the elements are still in memory, now add the  // whole enchillada to the document document.body.appendChild(elem);  // insertAdjacentHTML // ------------------ // nest an element within the nested div nested.insertAdjacentHTML(`afterbegin`,    `<div id="nestedWithin#nested">     This text will appear <i>above</i> the text of      my parent, that being div#nested.     Someone had the nerve to insert me using      <code>insertAdjacentHTML</code>    </div>`);  // Object.assign // ------------- // Use Object.assign to create an element and // assign properties/html to it in one go const newElem = Object.assign(   document.createElement(`div`),    { id: `myBrandnewDiv2`,      innerHTML: `div#myBrandnewDiv2 signing in.        I was <i>assigned</i> using <code>Object.assign</code>&hellip;`}); document.body.appendChild(newElem);  // insertAdjacentElement combined with Object.assign // ------------------------------------------------- // use the above technique combined with insertAdjacentElement newElem.insertAdjacentElement(   `beforeend`,     Object.assign(document.createElement(`span`),        { id: `myBrandnewnested2_nested`,          innerHTML: `<br>Me too! And appended I was            with <code>insertAdjacentElement</code>` }) );  // createDocumentFragment // ---------------------- // Use a document fragment to create/inject html const fragment = document.createDocumentFragment(); const mdnLnk = `https://developer.mozilla.org/en-US/` +     `docs/Web/API/Document/createDocumentFragment`; fragment.appendChild(   Object.assign(     document.createElement(`p`),      {innerHTML: `Regards from <code>createDocumentFragment</code>      (see <a href="${mdnLnk}">MDN</a>)`}) ); document.querySelector(`#myBrandnewDiv2`).appendChild(fragment);  // Create, but don't inject // ------------------------ const virtual = Object.assign(       document.createElement(`p`),        { innerHTML: `                <a href="#id1">id1</a>         <div id="id2">Hi!</div>         <p id="id3">Hi 2!</p>`,         classList: [`xyz`], } );  const prepareHtml4Reporting = html =>    html.replace(/</g, `&lt;`)     .replace(/\n\s+/g, `\n`)     .replace(/\n\n/g, `\n`);      document.body.insertAdjacentHTML(   `beforeend`,   `<h3>html only</h3><pre>${      prepareHtml4Reporting(virtual.innerHTML)}</pre>`);
body {   font: normal 12px/15px verdana, arial, sans-serif;   margin: 2rem; }  code {   background-color: #eee; }  .nested {   margin-left: 0.7rem;   max-width: 450px;   padding: 5px;   border: 1px solid #ccc; }

I have used some of these methods in this library (see /src/DOM.js), with a mechanism for sanitizing html before it is injecting.

like image 91
KooiInc Avatar answered Sep 28 '22 07:09

KooiInc


Html:

<div id="main"></div> 

JavaScript:

var tree = document.createDocumentFragment(); var link = document.createElement("a"); link.setAttribute("id", "id1"); link.setAttribute("href", "http://site.com"); link.appendChild(document.createTextNode("linkText"));  var div = document.createElement("div"); div.setAttribute("id", "id2"); div.appendChild(document.createTextNode("divText"));  tree.appendChild(link); tree.appendChild(div); document.getElementById("main").appendChild(tree); 

The main reason to use a documentFragment in stead of just adding the elements directly is speed of execution.

At this size it doesn't matter, but when you start adding hundreds of elements, you will appreciate doing it in-memory first :-)

With documentFragment you can construct a whole tree of DOM-elements in-memory and will not afffect the browser DOM untill the last moment.

Otherwise it forces the browser to update for every element, which sometimes can be a real pain to watch.

like image 34
Guidhouse Avatar answered Sep 28 '22 07:09

Guidhouse