3

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!

4
  • 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. Commented Nov 14, 2018 at 20:20
  • Best practices are creating DOM element objects and inserting text into those elements to safeguard against XSS Commented Nov 14, 2018 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 <script type="text/javascript">doBadThing()</script>. Unless you're escaping your inputs, or using a library that does, you should never set innerHTML directly with user-originating inputs. Commented Nov 14, 2018 at 20:24
  • content+='<h1>array[i]</h1>'; will not evaluate array[i] but instead print it as text. Commented Nov 14, 2018 at 20:32

4 Answers 4

5

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

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

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

Comments

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);
}

2 Comments

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.
I did think it seemed slower, but does that handle the case where the child doesn't exist?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.