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

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


当前回答

实际上,我想我会分享我想出的这个过于复杂但又简单的方法。。。也许有人会发现有用的东西。

/*Creates a new element - By Jamin Szczesny*/
function _new(args){
    ele = document.createElement(args.node);
    delete args.node;
    for(x in args){ 
        if(typeof ele[x]==='string'){
            ele[x] = args[x];
        }else{
            ele.setAttribute(x, args[x]);
        }
    }
    return ele;
}

/*You would 'simply' use it like this*/

$('body')[0].appendChild(_new({
    node:'div',
    id:'my-div',
    style:'position:absolute; left:100px; top:100px;'+
          'width:100px; height:100px; border:2px solid red;'+
          'cursor:pointer; background-color:HoneyDew',
    innerHTML:'My newly created div element!',
    value:'for example only',
    onclick:"alert('yay')"
}));

其他回答

可以使用以下方法从字符串创建有效的DOM节点:

document.createRange().createContextualFragment()

以下示例在页面中添加一个按钮元素,从字符串中获取标记:

让html='<button type=“button”>单击我</按钮>';let fragmentFromString=函数(strHTML){return document.createRange().createContextualFragment(strHTML);}let fragment=fragmentFromString(html);document.body.appendChild(片段);

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

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<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方法中实现了它。

使用insertAdjacentHTML()。它适用于所有当前浏览器,即使是IE11。

var mylist=文档.getElementById('mylist');mylist.insertAdjacentHTML('beforeend','<li>third</li>');<ul id=“mylist”><li>第一个</li><li>第二个</li></ul>

较新的DOM实现具有range.createContextualFragment,它以独立于框架的方式完成您所需的操作。

它得到了广泛的支持。不过,为了确保这一点,请在同一MDN链接中检查其兼容性,因为它会发生变化。截至2017年5月:

Feature         Chrome   Edge   Firefox(Gecko)  Internet Explorer   Opera   Safari
Basic support   (Yes)    (Yes)  (Yes)           11                  15.0    9.1.2