Slater Victoroff
Slater Victoroff

Reputation: 21914

How to get svg elements by class using regular expressions

I am trying to make an interactive graph out of an svg with paths for edges and circles for nodes. To find children of a node I want to be able to search edges for ids with a certain regex since the ids are all of the form: "node1_id node2_id". I've tried a number of solutions, including dollar dollar notation and placing regex directly into a find element by id, but I've had no luck. I can't find anything else that answers this and I'm pretty new to front-end dealings so I'm not sure if this might be something specific to svg or not.

$$('path[id^="\b10020 ([\d]+)"')
Error: SYNTAX_ERR: DOM Exception 12

document.getElementById("\b10020 ([\d]+)")
null

Are probably the two most sensible attempts I've made. all edges with node1_id being 10020 in this case.

<path fill="none" stroke-width="1.0"
              d="M -1026.321777,958.875610 C -987.123413,912.258789 -858.400574,901.130981 -811.783752,940.329346"
              id="10020 12050" stroke-opacity="1.0" stroke="#7dcb3c"/>

Being an example of one such edge that should have returned a match.

Upvotes: 0

Views: 1388

Answers (2)

Sergiu Dumitriu
Sergiu Dumitriu

Reputation: 11601

There is no CSS selector that accepts regular expressions, not even in the next level 4 version. [foo^=bar] means "an element whose foo attribute value begins exactly with the string bar". You can do several things:

  • if all you want is nodes with an ID beginning with 10020, then you can use $$("path[id^='10020 ']") but this will accept IDs that don't continue with other digits only
  • if you want the 10020 value to appear in the ID, regardless of the position, then use the path[id~='10020'] selector
  • if you really need to use regular expressions, then you have to walk the tree yourself and filter only the elements that you're interested in; you can optimize a bit by pre-filtering according to one of the selectors above, so that you have to check only the elements that do start with 10020

However, there is one big problem with your usecase: IDs may not contain spaces, that's an invalid SVG document. You really must use another attribute than id, maybe class is better suited for you, or if there is a semantic meaning to those numbers, define your own namespace and use new attributes in that namespace.

If you use class, then your selectors could also become simpler: $$("path.10020")

Upvotes: 0

Eric
Eric

Reputation: 97575

Were I doing it, I would change the markup to:

<path fill="none" stroke-width="1.0"
      d="M -1026.321777,958.875610 C -987.123413,912.258789 -858.400574,901.130981 -811.783752,940.329346"
      data-node-1="10020" data-node-2="12050" stroke-opacity="1.0" stroke="#7dcb3c"/>

Then using "single dollar notation" (aka, jQuery):

$('path[data-node-1="10020"]')

Upvotes: 1

Related Questions