Pappa S
Pappa S

Reputation: 343

How to find id and set attribute in javascript

Tried to set attribute value from html content by fs but not working. How to do it using javascript or nodejs.

public/index.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>

app.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/");
   }
   });

Upvotes: 0

Views: 521

Answers (2)

rishabh0211
rishabh0211

Reputation: 443

You can use cheerio like @Quentin mentioned.
OR You can add a placeholder for the href attribute in the html file.

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

And then you can replace the placeholder using string.replace() method.

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');
  });
});

Upvotes: 1

Quentin
Quentin

Reputation: 944534

When you read a file you get a string (or a buffer if you use different options).

Strings are not a DOM so you can't search it for elements.

You need to use something that can parse it into a DOM such as libxmljs or cheerio. Then you can use that to manipulate it and serialize it back to a string of HTML.

Upvotes: 0

Related Questions