html - With Nokogiri, how do you wrap the text contents of an element with a new tag? -
i have nokogiri::xml::element in looks this:
<div class="berg">this text!</div> what want extract text div (which nokogiri element) , wrap text new tag looks this:
<div class="berg"><span>this text!</span></div> the nokogiri .wrap functions seems wrap tags, not text contents new tag, wondering how wrap inter tag contents. cheers.
edit: took answer below , did in 1 line:
tag.inner_html = "<span>#{tag.inner_html}</span>"
you can set inner_html of div element. here's working example:
html = '<div class="berg">this text!</div>' doc = nokogiri::html.fragment(html) berg = doc.at('div.berg') # or xpath, or whatever method choose # wrap text in <span> berg.inner_html = "<span>#{berg.text}</span>" puts doc #=> <div class="berg"><span>this text!</span></div> the important part use of inner_html, adding in <span> element , putting existing text element inside it.
Comments
Post a Comment