gpt4 book ai didi

javascript - NodeJS - 如何使用 Javascript 在 HTML 文档中插入元素?

转载 作者:太空宇宙 更新时间:2023-11-04 01:23:43 26 4
gpt4 key购买 nike

我正在尝试使用 NodeJS 修改外部 HTML 文件(位于同一目录中)。在我的 index.js 文件中我写道:

fs.readFile('index.html', (err,html)=>{
if(err){
throw err;
}

html.body.innerHTML += '<div id = "asdf"></div>';

});

因为index.html是一个有效的文档。但它看起来没有正确读取它,因为我收到一个错误:

"TypeError: Cannot read property 'innerHTML' of undefined".

我猜 html 没有得到任何内容作为正文。

如何使用 JavaScript 更改 HTML?

最佳答案

这是一个使用 node-html-parse 的示例

HTML 文件

<html>
<body>
<div id="fist">yolo</div>
</body>
</html>

还有 Nodejs

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

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

const root = parse(html);

const body = root.querySelector('body');
//body.set_content('<div id = "asdf"></div>');
body.appendChild('<div id = "asdf"></div>');

console.log(root.toString()); // This you can write back to file!
});

考虑到下载量,可能有比node-html-parser更好的解决方案。例如,htmlparser2下载量更多,但看起来也更复杂:)

关于javascript - NodeJS - 如何使用 Javascript 在 HTML 文档中插入元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58264703/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com