Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I wrap the text contents of an element with a new tag?

I have a Nokogiri::XML::Element in 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 the Nokogiri Element) and then wrap the text with a new tag so it looks like this:

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

The Nokogiri .wrap functions seems to wrap tags, not their text contents with a new tag, I was wondering how you wrap the inter tag contents.

like image 313
MintDeparture Avatar asked May 10 '13 09:05

MintDeparture


People also ask

How do you wrap text in a tag?

Complete HTML/CSS Course 2022 If the line is large, then the <pre> tag won't wrap it by default. To wrap it, we need to use CSS. You can try to run the following code to learn about the usage of <pre> tag and how we can wrap text in HTML using CSS. We'll be using CSS <style> tag to add CSS to our HTML document.

What is wrap tag in HTML?

Definition and Usage The wrap attribute specifies how the text in a text area is to be wrapped when submitted in a form.


1 Answers

You can set the inner_html of the div element. Here's 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 the use of inner_html, adding in the <span> element and putting the existing text element inside it.

like image 100
Jon Cairns Avatar answered Nov 15 '22 07:11

Jon Cairns