Due to elements ids and classes being already assigned to elements and not being suitable to the purpose of a script, I figured doing:
<path class="marker" id="marker-1" fill="#A0C815"
d="M -4.1216879,-8.2290524 C -5.9110969,-12.502078 -7.23943,-15.753123 -7.3543753,-16.286999 l -0.2605528,-1.210168
c 0,0 -0.2841967,-2.894696 0.9582581,-4.746646
1.2424549,-1.851949 3.2568196,-3.327274 6.1627419,-3.327354 1.1162147,-3.1e-5 3.680967,-0.09509
5.715044,1.84306 z">SOME TEXT HERE</path>
Does not cause errors, does not cause browser errors, does not cause errors in inkscape or in linux's imageviewer.
This allows me to use SVGElement.textContent do make my script work.
I see this is syntactically valid, but would it be considered bad practice and worse, cause some unforeseen errors I might not be considering in my naivete?
SVGGeometry elements like path
, polygon
, polyline
, line
, circle
and ellipse
can't contain renderable child elements – at least they won't be rendered and may cause parsing issues in applications.
Nested non-renderable child-elements are fine such as:
<animate>
<description>
or <title>
Admittedly, "orphaned" text nodes – not to be confused with <text>
elements – within a geometry elements are an exception as most browsers will simply ignore these for rendering.
However, it's not recommended as less capable SVG renderers as used in office applications may not interpret these correctly.
Besides, you may run into trouble in terms of accessibility as screen readers may read the text content within the <path>
element.
If you need to store text data for your app better opt for data-attributes
(also compliant with SVG2 spec).
This is a common practice used for SVG maps - for instance saving country/region names that could be used for dynamic popups or tooltips.
marker1.onclick = (e) => {
let text = e.currentTarget.dataset.text;
alert(text)
}
<svg id="svg" viewBox="-7.64,-25.57,12.86,17.34">
<path id="marker1" fill="#A0C815" data-text="SOME TEXT HERE"
d="M -4.1216879,-8.2290524 C -5.9110969,-12.502078 -7.23943,-15.753123 -7.3543753,-16.286999 l -0.2605528,-1.210168 c 0,0 -0.2841967,-2.894696 0.9582581,-4.746646 1.2424549,-1.851949 3.2568196,-3.327274 6.1627419,-3.327354 1.1162147,-3.1e-5 3.680967,-0.09509 5.715044,1.84306 z"><title>SOME TEXT HERE</title></path>
</svg>
In the above example you'll see a native title tooltip due to the encloses <title>
element. When you click on the element you'll get an alert returning the data attributes value.
Heads up: It is true that data-attributes
are often stripped when editing and re-saving the SVG in a graphic application. So you should always keep a copy of your "hand-crafted" SVG markup.
As commented by Paul LeBeau: it is not explicitly forbidden in the current specs to add text nodes inside a geometry element. However you should avoid this for aforementioned reasons.