Node.js中操作DOM – jsdom

注意:jsdom 依赖 Node.js 10.x以上版本

jsdom is a pure-JavaScript implementation of many web standards, notably the WHATWG DOM and HTML Standards, for use with Node.js.

官网:https://github.com/jsdom/jsdom

安装:

npm i jsdom

使用示例:

const jsdom = require("jsdom");
const {
    JSDOM
} = jsdom;

const dom = new JSDOM(`<html><head></head><body></body></html>`);

const document = dom.window.document;

// 创建一个新的 div 元素
let newDiv = document.createElement("div");
// 给它一些内容
let newContent = document.createTextNode("设置 Text 文本!");
// 添加文本节点 到这个新的 div 元素
newDiv.appendChild(newContent);

//设置属性
newDiv.setAttribute("class","uni-list");
newDiv.setAttribute("style","color: red;");

//插入节点
document.querySelector('body').appendChild(newDiv)

console.log(document.querySelector("html").outerHTML);

Leave a Reply

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