我如何修改DocumentFragment中的所有节点?

问题描述 投票:0回答:1

我正在从一个范围中获取一个DocumentFragment,该范围是从一个Selection中选择的:

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

  1. 如何迭代地修改DocumentFragment中的所有节点?
  2. 如何重新插入此DocumentFragment以覆盖原始选择?

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

javascript dom range selection
1个回答
0
投票
// 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
...
© www.soinside.com 2019 - 2024. All rights reserved.