Search code examples
javascripthtmlnode.jsnode-html-parser

NodeJS - Can't insert an element to a HTML document using node-html-parser


When I try to append a HTML element to an existing using "body.appendChild" I get the error "TypeError: node.remove is not a function"

Here's what I'm doing:

const fs = require('fs');
const parse = require('node-html-parser').parse;

fs.readFile('./Iconfont/Icon_Map_Base.html', 'utf8', (err, html) => {
    if (err) {
        throw err;
    }

    const root = parse(html);
    const body = root.querySelector('body');
    body.appendChild('<h1>Hello World</h1>')
});

Solution

  • According to https://github.com/taoqf/node-html-parser/issues/202 the solution is to parse the html before appending it.

    body.appendChild(HtmlParser.parse(`<h1>header</h1>`));