我有一个表示元素的HTML字符串: '<li>text</li>'
。 我想将其附加到DOM中的元素(以个人状况为ul
)。 如何使用Prototype或DOM方法作到这一点? html
(我知道我能够在jQuery中轻松完成此操做,但不幸的是,咱们没有使用jQuery。) node
这也将起做用: jquery
$('<li>').text('hello').appendTo('#mylist');
感受更像是带有连接函数调用的jquery方式。 chrome
var jtag = $j.li({ child:'text' }); // Represents: <li>text</li> var htmlContent = $('mylist').html(); $('mylist').html(htmlContent + jtag.html());
使用jnerator app
迟了,但只是做为笔记; 函数
能够向目标元素添加一个琐碎的元素做为容器,并在使用后将其删除。 测试
//在chrome 23.0,firefox 18.0(即7-8-9和Opera 12.11)上进行了测试。 this
<div id="div"></div> <script> window.onload = function() { var foo, targetElement = document.getElementById('div') foo = document.createElement('foo') foo.innerHTML = '<a href="#" target="_self">Text of A 1.</a> '+ '<a href="#" onclick="return !!alert(this.innerHTML)">Text of <b>A 2</b>.</a> '+ '<hr size="1" />' // Append 'foo' element to target element targetElement.appendChild(foo) // Add event foo.firstChild.onclick = function() { return !!alert(this.target) } while (foo.firstChild) { // Also removes child nodes from 'foo' targetElement.insertBefore(foo.firstChild, foo) } // Remove 'foo' element from target element targetElement.removeChild(foo) } </script>
这是一种简单的方法: spa
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);
对于这个问题,我想我会想出一些复杂但又简单的方法,也许有人会发现有用的东西。 firefox
/*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')" }));