如何修改文档片段中的所有节点?



我从一个范围中获取一个文档片段,它来自一个选择:

var foo = window.getSelection().getRangeAt(0).cloneContents()

  1. 如何迭代修改文档片段中的所有节点?
  2. 如何重新插入此文档片段以覆盖原始选择内容?

https://codepen.io/MichaelArnoldOwens/pen/wvMwzLY

// i just used Selection to get a DocumenetFragment, but this can be applied to any DocumentFragment
var contents = window.getSelection().getRangeAt(0).extractContents()
// I generate a NodeList with querySelectorAll() and pass it the wildcard selector to get all the nodes
let list = contents.querySelectorAll('*')
// I instantiate a new DocumentFragment
let newFrag = new DocumentFragment()
// I iterate through the node list and make any modifications I want to each node before appending it to the new DocumentFragment
for (let i of list) {
i.style.color = 'red'
newFrag.appendChild(i)
}
// you can now append your new DocumentFragment to the DOM
...

最新更新