0.3.0 • Published 1 year ago

svg-visitor v0.3.0

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

svg-visitor

visit svg element use visitor pattern

Install

npm install svg-visitor

Usage

import { svgVisitor } from 'svg-visitor';

const svgDom = document.getElementByTagName('svg')[0]

svgVisitor(svgDom, {
  rectVisitor: function (rectDom) {
    const fill = rectDom.getAttribute('fill')
    if (fill === '#f00') {
      rectDom.setAttribute('fill', "#0f0")
    }
  }
})

before

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" baseProfile="full" width="40" height="40" >
  <rect width="40" height="40" x="0" y="0" id="0" fill="#f00"></rect>
</svg>

after

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" baseProfile="full" width="40" height="40" >
  <rect width="40" height="40" x="0" y="0" id="0" fill="#0f0"></rect>
</svg>

API

import { svgVisitor } from 'svg-visitor';

const svgDom = document.getElementByTagName('svg')[0]

svgVisitor(svgDom, {
  // visit all svg element under svgDom
  visitor: function(dom){},
  // visit <rect>...</rect>
  rectVisitor: function (rectDom) {},
  // visit <circle>...</circle>
  circleVisitor: function (circleDom) {},
  ...
})

Test

npm run-script test