如何将HTMLCollection插入页面?

时间:2019-03-28 15:27:30

标签: javascript htmlcollection

在下面的示例中,从包含HTML的字符串创建HTMLCollection。

是否有可能最终将HTML集合添加到另一个元素中,而不必添加其他周围的div或模板元素?

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>

1 个答案:

答案 0 :(得分:1)

由于insertAdjacentHTML期望第二个参数是DOM字符串,而不是HTML集合,因此您可以简单地将stringHTML传递给该函数:

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>