Can not do a replace operation, or set innerHTML or innerText on dom nodes in node with node-html-parser.
var HTMLParser = require('node-html-parser');
var content = `<h1>H1 Tag</h1> <img class="responsive-img img-wrap-right" src="/uploads/small_overwhelmed_debt_85b1046163.png?7215450.285000001" /><p> P Tag Contents</p>`
var html = HTMLParser.parse(content)
var domNodes = html.querySelectorAll('*')
for (const element of domNodes) {
if (element.outerHTML.includes('<p')) {
element.innerHTML = 'test'
console.log('element.innerHTML',element.innerHTML)
}
}
Output
element.innerHTML P Tag Test
Any idea why I can not set innerHTML?
Works just fine. Make sure you have an appropriate node/npm installed. I have
node -v; npm -v
v18.16.0
9.5.1
package.json:
{
"name": "parser",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"node-html-parser": "^6.1.5"
}
}
You could also try https://www.npmjs.com/package/jsdom
It's more popular/powerful.
BTW, don' use var
for god's sake...