admin管理员组

文章数量:1302341

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!

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!

Share Improve this question asked Nov 14, 2018 at 20:17 idudeidude 4,9228 gold badges37 silver badges51 bronze badges 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. – Mike Cluck Commented Nov 14, 2018 at 20:20
  • Best practices are creating DOM element objects and inserting text into those elements to safeguard against XSS – charlietfl 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 es 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. – Akhil F Commented Nov 14, 2018 at 20:24
  • content+='<h1>array[i]</h1>'; will not evaluate array[i] but instead print it as text. – connexo Commented Nov 14, 2018 at 20:32
Add a ment  | 

4 Answers 4

Reset to default 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 (putation of element's position and geometry). Historically, using document fragments could result in better performance.

Source: https://developer.mozilla/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

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>

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

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

本文标签: Changing HTML in JavaScript without innerHTMLStack Overflow