Skip to content

Instantly share code, notes, and snippets.

@zmts
Last active November 24, 2018 13:59
Show Gist options
  • Select an option

  • Save zmts/bfb7c6e5351e192b3cf7568f19407867 to your computer and use it in GitHub Desktop.

Select an option

Save zmts/bfb7c6e5351e192b3cf7568f19407867 to your computer and use it in GitHub Desktop.
Work with DOM in Node.js

Work with DOM in Node.js

const { JSDOM } = require('jsdom')

const htmlFragment = '<ul><li>one</li><li>two</li></ul>'
const jsDomFragment = JSDOM.fragment(htmlFragment)

jsDomFragment.querySelectorAll('li').forEach(li => {
  // make some operatons with DOM element, for example add some class
  li.classList.add('bold')
})

// serialize jsdom fragment to HTML
const updatedHTML = jsDomFragment.firstChild.outerHTML
console.log(updatedHTML) // >> <ul><li class="bold">one</li><li class="bold">two</li></ul>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment