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

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


当前回答

这也会奏效:

$('<li>').text('hello').appendTo('#mylist');

它感觉更像是一种带有链式函数调用的jquery方式。

其他回答

参观https://www.codegrepper.com/code-examples/javascript/convert+a+字符串+to+html+元素+in+js

const stringToHtml = function (str) {
    var parser = new DOMParser();
    var doc = parser.parseFromString(str, 'text/html');
    return doc.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方法中实现了它。

这里有一个简单的方法:

String.prototype.toDOM=function(){
  var d=document
     ,i
     ,a=d.createElement("div")
     ,b=d.createDocumentFragment();
  a.innerHTML=this;
  while(i=a.firstChild)b.appendChild(i);
  return b;
};

var foo="<img src='//placekitten.com/100/100'>foo<i>bar</i>".toDOM();
document.body.appendChild(foo);

最新JS示例:

<template id="woof-sd-feature-box">
<div class="woof-sd-feature-box" data-key="__KEY__" data-title="__TITLE__" data-data="__OPTIONS__">
    <h4>__TITLE__</h4>
    <div class="woof-sd-form-item-anchor">
        <img src="img/move.png" alt="">
    </div>
</div>

</template>

<script>
create(example_object) {
        let html = document.getElementById('woof-sd-feature-box').innerHTML;
        html = html.replaceAll('__KEY__', example_object.dataset.key);
        html = html.replaceAll('__TITLE__', example_object.dataset.title);
        html = html.replaceAll('__OPTIONS__', example_object.dataset.data);
        //convertion HTML to DOM element and prepending it into another element
        const dom = (new DOMParser()).parseFromString(html, "text/html");
        this.container.prepend(dom.querySelector('.woof-sd-feature-box'));
    }
</script>

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

/*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')"
}));