Node.js中操作dom – cheerio

cheerio 可以简单理解为node.js服务器端的jquery

官网:https://cheerio.js.org

安装:

npm i cheerio

使用示例:

const cheerio = require('cheerio')
const $ = cheerio.load('<html><head><title></title></head><body></body></html>')

//设置页面标题
$("title").text('new title')

//新增节点
$('body').append('<div class="content"></div>')
//添加class
$('.content').addClass('main')
//设置style样式
$('.content').css('color','red')

console.log($.html());

输出结果为:

<html><head><title>new title</title></head><body><div class="content main" style="color: red;"></div></body></html>

Leave a Reply

Your email address will not be published. Required fields are marked *