How to add HTML content of one node to another using Nokogiri
As the title says, I was wondering how to add the content of one node to another, like eg. Let's assume there is a node:
<li>
<a>I'm a link</a>
<p>I'm a <b>paragraph</b></p>
</li>
And another node I want to add content to the above:
<p>
<a>Link1</a>
<a>Link2</a>
<a>Link3</a>
<a>Link4</a>
</p>
Then unload the last node into the first like so:
<li>
<a>I'm a link</a>
<p>I'm a <b>paragraph</b></p>
<a>Link1</a>
<a>Link2</a>
<a>Link3</a>
<a>Link4</a>
</li>
source to share
I created two HTML DOM snippets based on your question. This line essentially merges the @doc.at_css("li") << @doc1.at_css("p").children
two pieces.
@doc.at("li")
returns the DOM Node
li
.
<<
adds @ doc1 DOM children Node``p
, which are four elements a
.
require 'nokogiri'
@doc = Nokogiri::HTML::DocumentFragment.parse <<-EOHTML
<li>
<a>I'm a link</a>
<p>I'm a <b>paragraph</b></p>
</li>
EOHTML
@doc1 = Nokogiri::HTML::DocumentFragment.parse <<-EOHTML
<p>
<a>Link1</a>
<a>Link2</a>
<a>Link3</a>
<a>Link4</a>
</p>
EOHTML
@doc.at("li") << @doc1.at("p").children
print @doc
<li>
<a>I'm a link</a>
<p>I'm a <b>paragraph</b></p>
<a>Link1</a>
<a>Link2</a>
<a>Link3</a>
<a>Link4</a>
</li>
source to share