Need help with htmlparser2?
Click the “chat” button below for chat support from the developer who created it, or find similar developers for support.

About the developer

fb55
3.0K Stars 328 Forks MIT License 1.1K Commits 1 Opened issues

Description

Forgiving HTML and XML parser

Services available

!
?

Need anything else?

Contributors list

htmlparser2

NPM version Downloads Build Status Coverage

The fast & forgiving HTML/XML parser.

Installation

npm install htmlparser2

A live demo of

htmlparser2
is available here.

Ecosystem

| Name | Description | | ------------------------------------------------------------- | ------------------------------------------------------- | | htmlparser2 | Fast & forgiving HTML/XML parser | | domhandler | Handler for htmlparser2 that turns documents into a DOM | | domutils | Utilities for working with domhandler's DOM | | css-select | CSS selector engine, compatible with domhandler's DOM | | cheerio | The jQuery API for domhandler's DOM | | dom-serializer | Serializer for domhandler's DOM |

Usage

htmlparser2
itself provides a callback interface that allows consumption of documents with minimal allocations. For a more ergonomic experience, read Getting a DOM below.
const htmlparser2 = require("htmlparser2");
const parser = new htmlparser2.Parser({
    onopentag(name, attributes) {
        /*
         * This fires when a new tag is opened.
         *
         * If you don't need an aggregated `attributes` object,
         * have a look at the `onopentagname` and `onattribute` events.
         */
        if (name === "script" && attributes.type === "text/javascript") {
            console.log("JS! Hooray!");
        }
    },
    ontext(text) {
        /*
         * Fires whenever a section of text was processed.
         *
         * Note that this can fire at any point within text and you might
         * have to stich together multiple pieces.
         */
        console.log("-->", text);
    },
    onclosetag(tagname) {
        /*
         * Fires when a tag is closed.
         *
         * You can rely on this event only firing when you have received an
         * equivalent opening tag before. Closing tags without corresponding
         * opening tags will be ignored.
         */
        if (tagname === "script") {
            console.log("That's it?!");
        }
    },
});
parser.write(
    "Xyz 

We use cookies. If you continue to browse the site, you agree to the use of cookies. For more information on our use of cookies please see our Privacy Policy.