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
检查,直到返回假值,然后您才知道所有子级都已移动!
javascript节点