D
D
Demigodd2020-04-29 12:16:48
ruby
Demigodd, 2020-04-29 12:16:48

How to add a div block to the beginning of the body using Nokogiri?

How to create a block with styles and content using Nokogiri and then add it to the beginning ? Block exampledivbody

<div style="color: red">
  Text
</div>


Examplebody
<body>
  Надо добавить его вот тут
  <p>Some Text</p>
   ...Content...
<body>


End result

Examplebody
<body>
  <div style="color: red">
    Text
  </div>
  <p>Some Text</p>
   ...
<body>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Valentin V., 2020-04-29
@Demigodd

you can do it like this

# наш контент в Nokogiri::HTML
nokogiri_html = Nokogiri::HTML(html_content)

# код нового элемента
new_element = '
<div style="color: red">
  Text
</div>
'

# добавление в начало body
nokogiri_html.at("body").children.first.add_previous_sibling(new_element)

# смотрим, что получилось
puts nokogiri_html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question