This is so...">

How do I wrap the text content of an element with a new tag?

I have a Nokogiri::XML::Element which looks like this:

 <div class="berg">This is some text!</div> 

What I want to do is just extract the text from the div (which is a Nokogiri element), and then wrap the text with a new tag so that it looks like this:

 <div class="berg"><span>This is some text!</span></div> 

It seems that the Nokogiri .wrap functions are in tags, not their textual content, the new tag, I was wondering how you wrap the contents of the inter-tags.

+4
source share
2 answers

You can set the inner_html of the div element. Here is a working example:

 html = '<div class="berg">This is some text!</div>' doc = Nokogiri::HTML.fragment(html) berg = doc.at('div.berg') # Or xpath, or whatever method you choose # Wrap the text in <span> berg.inner_html = "<span>#{berg.text}</span>" puts doc #=> <div class="berg"><span>This is some text!</span></div> 

The important part is to use inner_html , add to the <span> element and put the existing text element inside it.

+4
source

You would do:

 doc.search('div.berg text()').wrap('<span>') 
+3
source

Source: https://habr.com/ru/post/1480088/


All Articles