GULPF / nimquery

Nim library for querying HTML using CSS-selectors (like JavaScripts document.querySelector)
MIT License
134 stars 8 forks source link

Modify HTML DOM? #7

Closed ankush981 closed 5 years ago

ankush981 commented 5 years ago

Hello, just wanted to know if it's possible to modify HTML DOM using this library? If not, are there any options in the Nim ecosystem currently? Thanks! :smile:

GULPF commented 5 years ago

There's no special support for mutations in nimquery, but the xmltree module from the standard library (which nimquery uses) supports it. It's not a very ergonomic way to work with HTML, but it's the only thing available in Nim afaik. Example:

import xmltree
from htmlparser import parseHtml
import nimquery

let html = """
<!DOCTYPE html>
<html>
  <head><title>Example</title></head>
  <body>
    <p>1</p>
    <p>2</p>
    <p>3</p>
    <p>4</p>
  </body>
</html>
"""
let xml = parseHtml(newStringStream(html))
let elements = xml.querySelector("p")
elements[0].text = "replaced"
echo $xml
# Output:
# <document>
# <html>
#   <head><title>Example</title></head>
#   <body>
#     <p>replaced</p>
#     <p>2</p>
#     <p>3</p>
#     <p>4</p>
#   </body>
# </html>
# </document>
ankush981 commented 5 years ago

Thank you!