我有一个表示元素的HTML字符串:“<li>text</li>”。我想将它附加到DOM中的一个元素(在我的例子中是一个ul)。如何使用Prototype或DOM方法做到这一点?

(我知道我可以在jQuery中轻松做到这一点,但不幸的是,我们没有使用jQuery。)


当前回答

我添加了一个Document原型,它从字符串创建一个元素:

Document.prototype.createElementFromString = function (str) {
   const element = new DOMParser().parseFromString(str, 'text/html');
   const child = element.documentElement.querySelector('body').firstChild;
   return child;
};

用法:

document.createElementFromString("<h1>Hello World!</h1>");

其他回答

注意:大多数当前浏览器都支持HTML<template>元素,这提供了一种更可靠的方法来从字符串中创建元素。有关详细信息,请参阅下面Mark Amery的回答。

对于较旧的浏览器和node/jsdom:(在编写时还不支持<template>元素),请使用以下方法。这与库用来从HTML字符串中获取DOM元素的方法相同(IE需要额外的工作来解决innerHTML实现中的错误):

function createElementFromHTML(htmlString) {
  var div = document.createElement('div');
  div.innerHTML = htmlString.trim();

  // Change this to div.childNodes to support multiple top-level nodes.
  return div.firstChild;
}

注意,与HTML模板不同,这对于某些不能合法成为<div>的子元素的元素(如<td>s)不起作用。

如果您已经在使用一个库,我建议您坚持使用库批准的方法,从HTML字符串创建元素:

原型在其update()方法中内置了此功能。jQuery在其jQuery(html)和jQuery.parseHTML方法中实现了它。

以下是如何使用PrototypeJS(正如OP 12年前最初要求的那样):

HTML格式:

<ul id="mylist"></ul>

JS:

$('mylist').insert('<li>text</li>');

注意,这不是jQuery!

我自己找了很多,找到了一个很好的解决方案。

const stringToHTML = (str) => {
    var parser = new DOMParser();
    var doc = parser.parseFromString(str, 'text/html');
    return doc.body;
};

要转换的字符串:

'<iframe src="https://player.vimeo.com/video/578680903?h=ea840f9223&amp;app_id=122963" width="640" height="360" frameborder="0" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen title="Total Body Balance"></iframe>'

结果:

<body><iframe src="https://player.vimeo.com/video/578680903?h=ea840f9223&amp;app_id=122963" width="640" height="360" frameborder="0" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen="" title="Total Body Balance"></iframe></body>

我从这篇文章中得到了链接。(是否将HTML字符串转换为DOM元素?)

对我来说,我想找到一种将字符串转换为HTML元素的方法。如果您也有此需求,可以尝试以下方法

constfrag=document.createRange().createContextualFragment(`<a href=“/link.js”>js</a><a>去</a>`) constaCollection=frag.querySelectorAll(“a”)for(let[key,a]of Object.entries(aCollection)){console.log(a.getAttribute(“href”),a.textContent)}

答复

创建模板将模板的innerHTML设置为strim.trim()创建模板的子级数组返回子项、子项或

函数toElement(s=“”,c,t=document.createElement('template'),l='length'){t.innerHTML=s.trim();c=[…t.content.childNodes];返回c[l]>1?c: c[0]| |“”;}console.log(toElement());console.log(toElement(“”));console.log(toElement(“”));console.log(toElement('<td>With td</td>'));console.log(toElement('<tr><td>With t</td></tr>'));console.log(toElement('<tr><td>foo</td></tr><tr><td>bar</td></tr>'));console.log(toElement('<div><span><span>嵌套</span><span>填充</span></div>'));