【问题标题】:How can I modify all nodes in a DocumentFragment?如何修改 DocumentFragment 中的所有节点?
【发布时间】:2020-09-19 17:20:22
【问题描述】:

我从一个 Range 中得到一个 DocumentFragment,它来自一个 Selection:

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

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

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

【问题讨论】:

    标签: 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
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-06
      • 1970-01-01
      • 2012-01-23
      • 2011-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多