7

I want manipulate an html string, in vanillaJS I would do it something like this:

  let HTMLString = '<p>hello</p>
                            <style> 
                             p{
                               color:black
                              }
                            <p>world</p>
                             '
    const parser = new DOMParser();
    const doc = parser.parseFromString(HTMLString, "text/html");
    doc.querySelectorAll('style').forEach(item => item.remove())

this works in react aswell, but i believe since next compiles server side it just throws DOMParser is not defined, i've tried packages like html-react-parser, they just parse the html into react elements and offer very limited functionality after that, my last resort is using regex for this, but i've that's not a good idea.

any help in this would be good, thanks

ashish_arma
  • 165
  • 2
  • 8

1 Answers1

6

you may try node-html-parser component that I used for the similar reason in my next.js project: https://www.npmjs.com/package/node-html-parser

The idea is to use it server side in your getStaticProps() function like this:

import { parse } from 'node-html-parser';

const root = parse('<ul id="list"><li>Hello World</li></ul>');
console.log(root.querySelector('#list'));

As you can see you can traverse through this virtually generated dom using the standard ES6 query selectors, and there are also many more options so I found this one very powerful.