javascript节点_用JavaScript包装文本节点和元素

javascript节点

When you work on a site that relies on a given JavaScript toolkit, you unintentionally end up trying to solve problems within the bounds of the toolkit and not the language.  Such was the case when I tried wrapping text (possibly including HTML elements) with a DIV element.  Imagine the following HTML:

当您在依赖给定JavaScript工具包的网站上工作时,您无意间最终试图解决工具包(而非语言)范围内的问题。 当我尝试使用DIV元素包装文本(可能包括HTML元素)时就是这种情况。 想象以下HTML:


This is some text and <a href="">a link</a>.


And say you want to turn that into the following:

并说您想将其转换为以下内容:


<div>This is some text and <a href="">a link</a>.</div>


You could do a simple .innerHTML update on the parent but the problem with that is any event connections would be severed because innerHTML creates new elements from HTML.  Damn.  So it's time to retreat to basic JavaScript -- glory for some and failure for others.  Here's how to make it happen:

您可以对父级进行简单的.innerHTML更新,但是问题在于所有事件连接都会被切断,因为innerHTML从HTML创建了新元素。 该死的。 因此,是时候退缩到基本JavaScript了-为某些荣耀而为其他荣耀。 这是实现它的方法:


var newWrapper = document.createElement('div');
while(existingParent.firstChild) {
	newWrapper.appendChild(existingParent.firstChild);
}


Using a for loop wont work because childNodes is a live node collection, so moving it would affect the the indexes.  Instead we can do continuous firstChild checks on the parent until a falsy value is returned and then you know all children have been moved!

使用for循环无效,因为childNodes是活动节点集合,因此移动它会影响索引。 相反,我们可以对父级进行连续的firstChild检查,直到返回假值,然后您才知道所有子级都已移动!

翻译自: https://davidwalsh.name/text-nodes

javascript节点

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值