使用內置DOM方法或原型從HTML字符串建立新的DOM元素

我有一個表示元素的HTML字符串: '<li>text</li>' 。 我想將其附加到DOM中的元素(以個人狀況爲ul )。 如何使用Prototype或DOM方法作到這一點? html

(我知道我能夠在jQuery中輕鬆完成此操做,但不幸的是,咱們沒有使用jQuery。) node


#1樓

這也將起做用: jquery

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

感受更像是帶有連接函數調用的jquery方式。 chrome


#2樓

var jtag = $j.li({ child:'text' }); // Represents: <li>text</li>
var htmlContent = $('mylist').html();
$('mylist').html(htmlContent + jtag.html());

使用jnerator app


#3樓

遲了,但只是做爲筆記; 函數

能夠向目標元素添加一個瑣碎的元素做爲容器,並在使用後將其刪除。 測試

//在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>

#4樓

這是一種簡單的方法: 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);

#5樓

對於這個問題,我想我會想出一些複雜但又簡單的方法,也許有人會發現有用的東西。 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')"
}));
相關文章
相關標籤/搜索