繁体   English   中英

如何在 javascript 中查找 id 并设置属性

[英]How to find id and set attribute in javascript

尝试通过 fs 从 html 内容中设置属性值,但不起作用。 如何使用 javascript 或 nodejs 来做到这一点。

公共/索引.html:

<!DOCTYPE html>
<html>
<body>

<h1>My First Heading</h1>
<p>My first paragraph.</p>
<div>
<a href="#" id="reset">Link</a>
</div>

</body>
</html>

应用程序.js:

 var fs = require('fs');
 fs.readFile('./public/index.html', { encoding: 'utf-8' }, function(err, html) {
                if (err) {
                    console.log(err);
                } else {

                html.find('#reset').setAttribute("href", "http://localhost:4200/home/");
   }
   });

你可以像@Quentin 提到的那样使用cheerio
或者您可以在 html 文件中为href属性添加占位符。

<div id="reset" href="%%RESET_PLACEHOLDER%%">content</div>

然后您可以使用string.replace()方法替换占位符。

const fs = require('fs');

const path = __dirname + '/public/index.html'; //file path

fs.readFile(path, {encoding: 'utf8'}, (err, data) => {
  let dataToWrite = data.replace(/%%RESET_PLACEHOLDER%%/g, 'hrefVal');
  fs.writeFile(path, dataToWrite, (err) => {
    console.log('file written');
  });
});

当你读取一个文件时,你会得到一个字符串(如果你使用不同的选项,你会得到一个缓冲区)。

字符串不是 DOM,因此您无法在其中搜索元素。

您需要使用可以将其解析为 DOM 的东西,例如libxmljscheerio 然后您可以使用它来操作它并将其序列化回 HTML 字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM