rubyhpricot

How to append a new node in Hpricot


I have a DOM and I want to insert a new node using Hpricot. Here my DOM structure:

<html>
  <head>
  </head>
  <body>
    ...
    ...

  </body>
</html>

What I want is I have to insert a script tag as a last child of <body> something like:

<body>
  ...
  <script>
    console.log(document.cookie)
  </script>
</body>

This is what I have:

doc = Hpricot.XML(%{<html>
                     <head>
                      </head>
                      <body>
                        ...
                        ...
                      </body>
                    </html>
                   })

doc.at('body')

But now I'm not getting any desired method to move forward and the documentation of hpricot sucks. Has anyone done this before?


Solution

  • Achieved but using Nokigiri pasting it incase if someone want to do this

    Here the HTML

      h1 = Nokogiri::XML.parse %{<html>
          <head>
              <script>
                alert("hello");
              </script>
          </head>
          <body>
            <p> THIS IS WAR </p>
          </body>
        </html>}
    

    apend your tag (my case script tag) as last child of body

    h1.search('body').children.after(%{<script> alert ('Hello') </script>})
    

    Hope this help to some