java String Dom,使用内置DOM方法或原型从HTML字符串创建新的DOM元素

我有一个表示元素的HTML字符串: '

text' 。 我想将其附加到DOM中的元素(以我的情况为ul )。 如何使用Prototype或DOM方法做到这一点?

(我知道我可以在jQuery中轻松完成此操作,但不幸的是,我们没有使用jQuery。)

#1楼

这也将起作用:

$('

').text('hello').appendTo('#mylist');

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

#2楼

var jtag = $j.li({ child:'text' }); // Represents:

text

var htmlContent = $('mylist').html();

$('mylist').html(htmlContent + jtag.html());

#3楼

迟了,但只是作为笔记;

可以向目标元素添加一个琐碎的元素作为容器,并在使用后将其删除。

//在chrome 23.0,firefox 18.0(即7-8-9和Opera 12.11)上进行了测试。

window.onload = function() {

var foo, targetElement = document.getElementById('div')

foo = document.createElement('foo')

foo.innerHTML = 'Text of A 1. '+

'Text of A 2. '+

'


'

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

}

#4楼

这是一种简单的方法:

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="100foobar".toDOM();

document.body.appendChild(foo);

#5楼

对于这个问题,我想我会想出一些复杂但又简单的方法,也许有人会发现有用的东西。

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

}));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值