【问题标题】:How can I modify all nodes in a DocumentFragment?如何修改 DocumentFragment 中的所有节点?
【发布时间】:2020-09-19 17:20:22
【问题描述】:
【问题讨论】:
标签:
javascript
dom
range
selection
【解决方案1】:
// 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
...