NodeJS - 如何使用 Javascript 在 HTML 文档中插入元素? [英] NodeJS - How to insert an element in a HTML document using Javascript?

查看:40
本文介绍了NodeJS - 如何使用 Javascript 在 HTML 文档中插入元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to use NodeJS to modify an external HTML file (which is located in the same directory). In my index.js file I write:

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

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

});

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

As index.html is a valid document. But it doesn't look to be reading it properly, as I get as an error:

类型错误:无法读取未定义的属性innerHTML"".

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

我猜 html 没有得到任何东西作为正文.

I guess that html is not getting anything as body.

如何使用 JavaScript 更改 HTML?

How can I do changes in HTML using JavaScript?

推荐答案

这里是一个使用 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 的下载量要多得多,但看起来也更复杂 :)

There might be better solutions than node-html-parser, considering the amount of downloads. For example, htmlparser2 has much more downloads, but it also looks more complex :)

这篇关于NodeJS - 如何使用 Javascript 在 HTML 文档中插入元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆