Extract <svg> element using document.evaluate ()?

I am trying to use document.evaluate()

to retrieve specific children from an element <svg>

. But I'm having trouble just extracting <svg>

. I can extract everything before <svg>

, but not further. For example, this works well:

document.evaluate('//*[@id="chart"]/div/div[1]/div', document, null, XPathResult.ANY_UNORDERED_NODE_TYPE, null).singleNodeValue)

      

This gives me (shorthand):

<div style="position: absolute; left: 0px; top: 0px; width: 100%; height: 100%;" aria-label="Et diagram.">
    <svg width="600" height="400" aria-label="Et diagram." style="overflow: hidden;"></svg>
    <div aria-label="En repræsentation i tabelformat af dataene i diagrammet." style="position: absolute; left: -10000px; top: auto; width: 1px; height: 1px; overflow: hidden;"></div>
</div>

      

and then I would take a simple

//*[@id="chart"]/div/div[1]/div/svg

      

would give it to me <svg>

but nothing works. Have tried all types of answers:

for (var type=XPathResult.ANY_TYPE; type<XPathResult.FIRST_ORDERED_NODE_TYPE+1; type ++) {
   console.dir(
      document.evaluate('//*[@id="chart"]/div/div[1]/div/svg', document, null, type, null)
   );   
}    

      

I am getting either invalidIteratorState

null singleNodeValue

or snapshotLength

of 0.

demo -> http://jsfiddle.net/hw79zp7j/

Are there any restrictions in evaluate()

that I haven't heard of, or am I just doing it completely wrong?

To clarify, my ultimate goal is to be able to extract, for example, google visualization xAxis

<text>

in one line of code. As of now (see demo), I have to iterate through <svg>

with multiple querySelectorAll

/ getElementsByTagName

etc, which is not very readable, requires no maintenance or elegance. It would be nice to grab xpath

from google developer tools and reuse it in one line.

+3


source to share


1 answer


SVG elements are in a namespace http://www.w3.org/2000/svg

and to select elements in a namespace with XPath you need to bind the prefix to the namespace URI and use that prefix in your path to define the element names eg. svg:svg

... So use resolver as the third argument evaluate

, which maps a prefix you can choose (for example svg

) to the namespace URI mentioned above.



document.evaluate('//*[@id="chart"]/div/div[1]/div/svg:svg', document, 
                                function(prefix) { 
                                    if (prefix === 'svg') 
                                    { 
                                        return 'http://www.w3.org/2000/svg';
                                    }
                                    else
                                    {
                                        return null;
                                    }
                                }, type, null)

      

+5


source







All Articles