loading words...

May 26, 2019 17:56:30

javascript html parsing

by @swizecteller | 203 words | 🐣 | 116💌

Swizec Teller

Current day streak: 0🐣
Total posts: 116💌
Total words: 32303 (129 pages 📄)

If you ever need to parse HTML in JavaScript, remember that your browser has a wonderful HTML parser built right in. You don't even need a library.

Something like this works great 0kb added to your bundle :P


Added a feature to techletter.app that lets you click a button to reload a screenshot. But we don't want that button to show up in the final export.

So I started looking for a way to parse HTML. Can't use regex because html is not a regular language ...



After some Googling it hit me: You don't need an HTML parser for JavaScript. IT'S ALREADY THERE! 🤦‍♀️


So how does this work then? Easy

1) You create a DOM node, no need to render it

2) Set its innerHTML to your input

Browser magically parses that HTML into a DOM tree 👌


You can then do whatever you want using regular DOM manipulation functions. I know you're probably using React, Vue, or whatever so you may have forgotten these exist.

They're still there :)


Once you're done manipulating the DOM, use .innerHTML to get the final output.

And that's how you can use the browser itself to parse and stringify HTML. Feels like a trick but it's great

Originally published at twitter.com

  • 1

    @swizecteller - nice observation and thanks for re-pointing that out.

    Brian Ball avatar Brian Ball | May 26, 2019 18:16:24
contact: email - twitter / Terms / Privacy