Remi
Remi

Reputation: 5357

How to insert HTMLCollection into the page?

In the following example, a HTMLCollection is created from a string containing HTML.

Is it possible to eventually add the HTML collection into another element, without having to add an additional surrounding div or template element?

const stringHTML = `
	<div>
  	<h1>This is a div</h1>
	  <div>
  		<p>inner div</p>
		</div>
  </div>
  <div>
  	<h2>Another div</h2>
  </div>
`;


/**
 * @param html {String} Representing a single HTML element
 * @return {HTMLCollection} The newly created element
 */
const stringToHTMLCollection = function(html) {
  /** @type {HTMLElement} */
  const template = document.createElement('template');
  html = html.trim(); // Never return a text node of whitespace as the result
  template.innerHTML = html;
  return template.content.children;
}

console.log(stringToHTMLCollection(stringHTML));

// This works.
Object.entries(stringToHTMLCollection(stringHTML)).forEach(([key, element])  => {
      result.insertAdjacentElement('beforeend', element);
    });
    
// However isn't there a more elegant way using something similar to insertAdjecentHTML?
<div id="result"></div>

Upvotes: 0

Views: 900

Answers (1)

FZs
FZs

Reputation: 18619

Since the insertAdjacentHTML expects the second argument to be a DOM string, not an HTML collection, you can simply pass the stringHTML to that function:

const stringHTML = `
	<div>
  	<h1>This is a div</h1>
	  <div>
  		<p>inner div</p>
		</div>
  </div>
  <div>
  	<h2>Another div</h2>
  </div>
`;


/**
 * @param html {String} Representing a single HTML element
 * @return {HTMLCollection} The newly created element
 */

result.insertAdjacentHTML('beforeend', stringHTML);
<div id="result"></div>

Upvotes: 1

Related Questions