I have a big web project with a lot of static html files. Is there a way to manipulate these files with node.js? I mean that if I want to change tabindex on 50 files can I do some selection like
$('input.myClass').attr('tabindex', '-1');
and apply it on all? Can I manipulate my project's files this way? Modifying, replacing strings depending on some criteria?
The only alternative I have for automating large changes is bash(for now) but I don't think it's a good idea to spend that much time to build custom scripts for css selectors.
Here is a simple script using cheerio that demonstrates how to manipulate html files. assuming the html looks like this:
<!DOCTYPE html>
<html>
<head>
<title>My Test Page</title>
</head>
<body>
<ul id="fruits">
<li class="apple">Apples</li>
<li class="orange">Orange</li>
<li class="pear">Pear</li>
</ul>
</body>
</html>
The script to add tabindex would look like this:
#!/usr/bin/env node
var fs = require('fs'),
cheerio = require('cheerio');
fs.readFile('index.html', { encoding:'utf-8' }, function(err, data) {
if (err) throw err;
var $ = cheerio.load( data );
var apple = $('.apple');
apple.attr('tabindex', '-1');
// now write the file out
console.log( $.html() );
});
The modified html now looks like this:
<!DOCTYPE html>
<html>
<head>
<title>My Test Page</title>
</head>
<body>
<ul id="fruits">
<li class="apple" tabindex="-1">Apples</li>
<li class="orange">Orange</li>
<li class="pear">Pear</li>
</ul>
</body>
</html>