如何在一个特定的位置添加一个子节点 [英] How can I add a child to a node at a specific position?
本文介绍了如何在一个特定的位置添加一个子节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个有两个孩子的节点:一个HTML文本和一个HTML元素。
I have a node which has two children: an HTML text and an HTML element.
<h1 id="Installation-blahblah">Installation on server<a href="#Installation-blah" class="wiki-anchor">¶</a>
</h1>
在这种情况下,HTML文本是:
In this case the HTML text is:
Installation on server
和HTML元素: p>
and the HTML element:
<a href="#Installation-blah" class="wiki-anchor">anchor;</a>
然后我创建一个这样的节点:
I then create a node like this:
span_node = Nokogiri::HTML::Node.new('span',doc)
span_node['class'] = 'edit-section'
link_node = Nokogiri::HTML::Node.new('a',doc)
link_node['href'] = "/wiki/#{page_id}/#{@page.title}/edit?section=#{section_index}"
link_node['class'] = 'icon icon-edit'
link_node.content = 'mylink'
span_node.add_child(link_node)
现在,要将上面的节点添加到主节点,我使用以下内容:
Now, to add the above node to the main node I use the following:
node.add_child(span_node)
这将追加到最后的跨度节点。如何将 span_node
放在所有孩子面前?
This appends the span node at the end. How can I put the span_node
in front of all children?
推荐答案
感谢Pesto您的几乎正确的解决方案。
Thanks Pesto for your almost correct solution.
工作解决方案是:
node.children.first.add_previous_sibling(span_node)
这篇关于如何在一个特定的位置添加一个子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文