Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a child to a node at a specific position?

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">&para;</a>
</h1>

In this case the HTML text is:

Installation on server 

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)

This appends the span node at the end. How can I put the span_node in front of all children?

like image 263
Manuel Avatar asked Jun 02 '09 14:06

Manuel


People also ask

How do you append a child at a specific position?

appendChild() The appendChild() method of the Node interface adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position.

What is difference between append and appendChild?

append() can append several nodes and strings, whereas Node. appendChild() can only append one node.

How do I select a specific child in Javascript?

Select the parent element whose child element is going to be selected. Use . querySelector() method on parent. Use the className of the child to select that particular child.

How do you get children of node?

To get all child nodes, including non-element nodes like text and comment nodes, use Node. childNodes .


1 Answers

Thanks Pesto for your almost correct solution.

The working solution is:

node.children.first.add_previous_sibling(span_node)
like image 184
Manuel Avatar answered Sep 26 '22 15:09

Manuel