0
<svg>
  <g id="g1" transform="translate(100 80)"/>
</svg>

<script>
  var tr_value = document.getElementById("g1").getAttribute("transform");
  alert(tr_value);   // result: translate(100 80)      need: 100
</script>

Hi to experts, tell me how to get the value of the attribute parameter in case the attribute has several parameters, and they, in turn, have several values. In the example above, I would like to get a value of 100 into a variable. I really hope that in Javascript there is a beautiful method for this. And then the first thing that comes to mind is to parse text or regular expressions.

2
  • JavaScript doesn't directly know anything about SVG; the attribute value is just text. You have to parse it yourself, probably with a regular expression. Commented Jan 6, 2020 at 16:08
  • Over and over I see people calling functions then not checking the return. When a function returns something it might be successful and it may not. Like so many others you are not checking the return before use. Check the return from getElementById before calling getAttribute, then check the return from getAttribute too before use. Commented Jan 6, 2020 at 16:23

1 Answer 1

1

You'll have to write a regular expression or string parser to do this.

e.g. .*\((\d*) \d*\)

let tr_value = document.getElementById("g1").getAttribute("transform")
let regex = /.*\((\d*) \d*\)/g
let matches = regex.exec(tr_value)
console.log(matches[1]) // "100"
<svg>
  <g id="g1" transform="translate(100 80)"/>
</svg>

.*\((\d*) \d*\) Regexplanation:

.* - Any sequence of characters
\( - followed by a open parenthesis
( - begin a capture group for matches array
\d* - match any sequence of numerical digits
) - end the capture group
- followed by a space
\d* - followed by any sequence of numeric digits
\) - followed by a close parenthesis

Note: the matched value will be a string, so you may need to cast it into a numeric value if that is what your code expects.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for your answer. Very fast and informative. I would even say too fast and too informative)))

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.