2

Let's say my code was something pretty simple like this:

let content = "";

for(let i=0; i<array.length; i++){
    content+='<h1>array[i]</h1>';
}

document.getElementById('some_id').innerHTML = content;

I don't like the idea of putting HTML in my JavaScript code, but I don't know any other way of inserting elements into the DOM without using innerHTML, JQuery's html() method, or simply creating new DOM elements programmatically.

In the industry or for best practices, what's the best way to insert HTML elements from JavaScript?

Thanks in advance!

idude
  • 4,654
  • 8
  • 35
  • 49
  • You can use `document.createElement` and `nodeYouWishToExtend.appendChild(nodeYouCreated)`. For another way to do it all together, you can look at frameworks like React, Angular, Vue, Knockout, etc. – Mike Cluck Nov 14 '18 at 20:20
  • Best practices are creating DOM element objects and inserting text into those elements to safeguard against XSS – charlietfl Nov 14 '18 at 20:21
  • ps your hunch that writing html in javascript is "bad" is mostly correct. I don't know where `array` comes from, but assuming its something users can change, they could sneak in some "unsafe" values. For example ``. Unless you're escaping your inputs, or using a library that does, you should never set innerHTML directly with user-originating inputs. – A F Nov 14 '18 at 20:24
  • `content+='

    array[i]

    ';` will not evaluate `array[i]` but instead print it as text.
    – connexo Nov 14 '18 at 20:32

4 Answers4

3

You can use a DOMParser and ES6 string literals:

const template = text => (
`
<div class="myClass">
    <h1>${text}</h1>
</div>
`);

You can create a in memory Fragment:

const fragment = document.createDocumentFragment();
const parser = new DOMParser();
const newNode = parser.parseFromString(template('Hello'), 'text/html');
const els = newNode.documentElement.querySelectorAll('div');
for (let index = 0; index < els.length; index++) {
  fragment.appendChild(els[index]);  
}
parent.appendChild(fragment);

Since the document fragment is in memory and not part of the main DOM tree, appending children to it does not cause page reflow (computation of element's position and geometry). Historically, using document fragments could result in better performance.

Source: https://developer.mozilla.org/en-US/docs/Web/API/Document/createDocumentFragment

Basically you can use whatever template you want because it's just a function that return a string that you can feed into the parser.

Hope it helps

NickHTTPS
  • 744
  • 4
  • 16
2

You can use the createElement() method

In an HTML document, the document.createElement() method creates the HTML element specified by tagName, or an HTMLUnknownElement if tagName isn't recognized.

Here is an example,

document.body.onload = addElement;

function addElement () { 
  // create a new div element 
  var newDiv = document.createElement("div"); 
  // and give it some content 
  var newContent = document.createTextNode("Hi there and greetings!"); 
  // add the text node to the newly created div
  newDiv.appendChild(newContent);  

  // add the newly created element and its content into the DOM 
  var currentDiv = document.getElementById("div1"); 
  document.body.insertBefore(newDiv, currentDiv); 
}
<!DOCTYPE html>
<html>
<head>
  <title>||Working with elements||</title>
</head>
<body>
  <div id="div1">The text above has been created dynamically.</div>
</body>
</html>
onyx
  • 1,588
  • 7
  • 14
0

Creating the element programmatically instead of via HTML should have the desired effect.

const parent = document.getElementById('some_id');
// clear the parent (borrowed from https://stackoverflow.com/questions/3955229/remove-all-child-elements-of-a-dom-node-in-javascript)

while (parent.firstChild) {
    parent.removeChild(parent.firstChild);
}

// loop through array and create new elements programmatically
for(let i=0; i<array.length; i++){
    const newElem = document.createElement('h1');
    newElem.innerText = array[i];
    parentElement.appendChild(newElem);
}
Dr_Derp
  • 1,185
  • 6
  • 17
  • Clearing the child nodes using the while loop I have found is slower if you have a lot of nodes, I have been liking this one liner el.parentNode.replaceChild(el.cloneNode(false), el) the element is cloned with the false flag which makes a copy without any children then the element is replaced with it's leaner self. – Harry Chilinguerian Nov 14 '18 at 21:21
  • I did think it seemed slower, but does that handle the case where the child doesn't exist? – Dr_Derp Nov 15 '18 at 17:31
0

A flexible and more faster (efficient) way to insert HTML elements using JavaScript's insertAdjacentHTML method. It allows you to specify exactly where to place the element. Possible position values are:

  • 'beforebegin'
  • 'afterbegin'
  • 'beforeend'
  • 'afterend'

Like this:

 document.getElementById("some_id").insertAdjacentElement("afterbegin", content);

Here's a Fiddle example

Juan Marco
  • 3,081
  • 2
  • 28
  • 32