Nodejs as a back-end language, direct DOM manipulation is a violation of the separation principle.
But if it is a small personal site, a little bit more flexible is not bad.
Here is the Cheerio plugin, which is based on jquery and is slightly streamlined to provide NODEJS with DOM operations like jquery
PS: originally Jsdom is also a choice, but unfortunately the latest version of Jsdom no longer support Nodejs
Let's look at an example:
//This method reads the file name from the Filelist.txt and adds it to the Index.html class as Listselect under the Select Tag function getfilelist(){ varContent = Fs.readfilesync ('./index.html '); $ = cheerio.load (content); $(' Select.listselect ').Empty();//Avoid duplication, clear all child tags under label before loadingLinereader.eachline ('./filelist.txt ', function(line,last){ //linereader is a Nodejs plugin that reads files by line and can be installed on its own varFile = Line.substr (Line.lastindexof ("')+1); $(' Select.listselect '). Append (' <option class= ' listoption ' value= '+file+' > '+file+' </option> ');if(last) {Fs.writefile ("./index.html", $.html (), function(err) {if(err) throw err; Console.log("Saved"); }); return false; }});
About why there would be
$ = cheerio.load(content);
This kind of writing is really very tangled, must be $ this symbol or it will go wrong, I personally understand that it seems to be consistent with the selector in jquery and deliberately write this
More operations can be seen
Https://npmjs.org/package/cheerio
Official documents or the following translation documents
https://cnodejs.org/topic/5203a71844e76d216a727d2e
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
node. JS Notes (10) Nodejs and DOM operations