在 JavaScript DOM 中拆分节点内容
我有一个场景,我需要将节点拆分为给定的祖先,例如
<strong>hi there, how <em>are <span>you</span> doing</em> today?</strong>
需要拆分为:
<strong>hi there, how <em>are <span>y</span></em></strong>
以及
<strong><em><span>ou</span> doing</em> today?</strong>
我将如何执行此操作?
I have a scenario where I need to split a node up to a given ancestor, e.g.
<strong>hi there, how <em>are <span>you</span> doing</em> today?</strong>
needs to be split into:
<strong>hi there, how <em>are <span>y</span></em></strong>
and
<strong><em><span>ou</span> doing</em> today?</strong>
How would I go about doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一个适用于使用
Range
的现代浏览器的解决方案。对于 IE < 可以做类似的事情9 使用TextRange
,但我使用 Linux,所以我无法轻松访问这些浏览器。我不确定您想要该函数做什么,返回节点或只是进行内联替换。我只是猜测并进行了内联替换。演示: jsbin
它需要一个
TextNode
作为node,尽管它可以与
Element
一起使用;根据 Range.setStart 的行为,偏移量的功能会有所不同Here is a solution that will work for modern browsers using
Range
. Something similar could be done for IE < 9 usingTextRange
, but I use Linux so I don't have easy access to those browsers. I wasn't sure what you wanted the function to do, return the nodes or just do a replace inline. I just took a guess and did the replace inline.Demo: jsbin
It expects a
TextNode
fornode
, although it will work with anElement
; the offset will just function differently based on the behavior of Range.setStart请参阅方法
Text.splitText
。See the method
Text.splitText
.不确定这是否对您有帮助,但这就是我想出的...
向函数传递一个您希望移动到的元素和节点标签名称字符串。
Not sure if this helps you, but this is what I came up with...
Pass the function an element and a node tag name string you wish to move up to.