我有一个表示元素的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')"
}));

其他回答

这是我的工作代码

我想将“文本”字符串转换为HTML元素

var diva = UWA.createElement('div');
diva.innerHTML = '<a href="http://wwww.example.com">Text</a>';
var aelement = diva.firstChild;

注意:大多数当前浏览器都支持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方法中实现了它。

我添加了一个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>");

HTML5和ES6

<模板>

Demo

“使用严格”;/****@作者xgqfrms*@许可证MIT*@版权xgqfrms*@description HTML5模板*@扩增*@示例**//*<模板><h2>鲜花</h2><img src=“https://www.w3schools.com/tags/img_white_flower.jpg"></template><模板><div class=“myClass”>我喜欢:</div></template>*/常量showContent=()=>{//let temp=document.getElementsByTagName(“template”)[0],let temp=document.querySelector(`[data tempalte=“tempalte img”]`),clone=临时内容克隆节点(true);document.body.appendChild(克隆);};const templateGenerator=(datas=[],debug=false)=>{让result=``;//let temp=document.getElementsByTagName(“template”)[1],let temp=document.querySelector(`[data tempalte=“tempalte links”]`),item=temp.content.querySelector(“div”);for(设i=0;i<data.length;i++){let a=document.importNode(item,true);a.textContent+=数据[i];document.body.appendChild(a);}返回结果;};const arr=[“奥迪”、“宝马”、“福特”、“本田”、“捷豹”、“日产”];if(document.createElement(“template”).content){console.log(“是!浏览器支持模板元素”);模板生成器(arr);setTimeout(()=>{showContent();}, 0);}其他{console.error(“否!浏览器不支持模板元素”);}@字符集“UTf-8”;/*测试.css*/:根目录{--颜色:#000;--默认cololr:#fff;--新的cololr:#0f0;}[数据class=“links”]{颜色:白色;背景色:道奇蓝;填充:20px;文本对齐:居中;边距:10px;}<!DOCTYPE html><html lang=“zh-Hans”><head><meta charset=“UTF-8”><meta name=“viewport”content=“width=设备宽度,初始比例=1.0”><meta http equiv=“X-UA-Compatible”content=“ie=edge”><title>模板测试</title><!--[如果lt IE 9]><script src=“https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.js“></script><![endif]--></head><body><章节><h1>模板测试</h1></section><template data tempalte=“tempalte img”><h3>花卉图像</h3><img src=“https://www.w3schools.com/tags/img_white_flower.jpg"></template><template data tempalte=“tempalte links”><h3>链接</h3>我喜欢:</div></template><!-- js--></body></html>

答复

创建模板将模板的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>'));