How to use DOMParser in next.js?
Asked Answered
W

2

8

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

Weak answered 10/6, 2021 at 5:26 Comment(4)
does this question (Trying to use the DOMParser with nodejs) address your question?Kriskrischer
i don't believe we can use those packages in React/NextWeak
Hi, you can do that in a "useEffect" call, as useEffect is only called client-side.Krantz
Are you trying to run this code on the server-side (inside getStaticProps/getSeverSideProps)?Frons
A
8

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.

Acyl answered 4/8, 2021 at 14:42 Comment(0)
C
1

Cheerio seems to be another popular option: https://github.com/cheeriojs/cheerio

As shown on their README:

import * as cheerio from 'cheerio';
const $ = cheerio.load('<h2 class="title">Hello world</h2>');

$('h2.title').text('Hello there!');
$('h2').addClass('welcome');

$.html();
//=> <html><head></head><body><h2 class="title welcome">Hello there!</h2></body></html>
Cherisecherish answered 20/8, 2024 at 13:15 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.