0

在以下示例中,从包含 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>

4

1 回答 1

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>

于 2019-03-28T15:38:29.377 回答