Implement an HTML parser in pure JS(TS) without relying on any libraries. Supports basic functionalities such as querying, adding, modifying, removing elements and converting to code.
中文文档
install:
npm i pure-js-html-parser
use:
import{Parser}from'pure-js-html-parser'consttxt=`<div a='a' b="2">a</div>`const$=newParser(txt)// Get the parsed data$.parserData/** * [ { tag: "div", value: "", type: "tag", children: [ { tag: "", value: "a", type: "text", children: [], attributes: [], }, ], attributes: [ { key: "a", value: "a", }, { key: "b", value: "2", }, ], }, ] */exportinterfaceIParseHtmlAttribute{key:string;value:string|undefined;}exporttypeIParseValueType="tag"|"text";exportinterfaceIParseHtmlItem{tag:string;value:string;type:IParseValueType;children:IParseHtmlItem[];attributes:IParseHtmlAttribute[];}If the node contains a tag:<div></div>, then the type istag. The output is:
{tag:'div',value:'',type:'tag',children:[],attributes:[{key:'id',value:'a'}]}If it is text, such as the contenta or thea within<div>a</div>, then the type istext. The output is:
{tag:'',value:'a',type:'text',children:[],attributes:[]}consttxt=`<div a='a' b="2">a</div>`const$=newParser(txt)// query tag$.query('div')// query class$.query('.a')// query id$.query('#a')// query all$.queryAll('.a')consttxt=`<div a='a' b="2">a</div>`const$=newParser(txt)// Insert an element at the end of the ".a" element$.push({tag:'div',value:'',type:'tag',children:[],attributes:[]},'.a')// Insert an element at the end$.push({tag:'div',value:'',type:'tag',children:[],attributes:[]})consttxt=`<div a='a' b="2">a</div>`const$=newParser(txt)// Modify the attribute of the ".a" element'$.modify('.a',(item)=>{item.attributes[2].value="a2"returnitem})consttxt=`<div a='a' b="2"><div></div></div>`const$=newParser(txt)$.remove('.b')consttxt=`<div a='a' b="2"><div></div></div>`const$=newParser(txt)$.transform()