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.
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.
Definition and Usage The wrap attribute specifies how the text in a text area is to be wrapped when submitted in a form.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With