Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Implement an HTML parser in pure JS(TS) without relying on any libraries.

NotificationsYou must be signed in to change notification settings

rni-l/pure-js-html-parser

Repository files navigation

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.

中文文档

Quickly use

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",        },      ],    },  ] */

Data structure

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:[]}

Query elements

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')

Add element

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:[]})

Modify element

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})

Remove element

consttxt=`<div a='a' b="2"><div></div></div>`const$=newParser(txt)$.remove('.b')

Transform to HTML code

consttxt=`<div a='a' b="2"><div></div></div>`const$=newParser(txt)$.transform()

TODO

  • 重构整个功能实现
  • 处理 svg 的标签
  • 处理注释

About

Implement an HTML parser in pure JS(TS) without relying on any libraries.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp