首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何修改DocumentFragment中的所有节点?

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

Stack Overflow用户
提问于 2020-06-01 11:59:54
回答 1查看 64关注 0票数 1

我从一个范围得到一个DocumentFragment,这是从一个选择中得到的:

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

如何迭代地修改DocumentFragment?

  • How中的所有节点,我可以重新插入这个DocumentFragment来覆盖原始的选择吗?

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

EN

回答 1

Stack Overflow用户

发布于 2020-06-01 12:49:52

代码语言:javascript
复制
// 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
...
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62131689

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档