xPath and svg
// hack to shove some html on the page since snippet.zone
// quick editor does not yet suppor HTML :P
document.body.innerHTML += `
<svg style="overflow:visible">
<rect x="10" y="10" fill="red" width="30" height="10" />
<rect x="10" y="20" fill="blue" width="30" height="10" />
<rect x="10" y="30" fill="purple" width="30" height="10" />
</svg>
`;
const svgPrefix = pre => pre === 'svg' && 'http://www.w3.org/2000/svg';
// https://stackoverflow.com/questions/31162358/extract-svg-element-by-using-document-evaluate
let els = document.evaluate(
'//svg:svg/*[@fill="blue"]',
document,
svgPrefix,
XPathResult.ANY_TYPE,
null
);
const results = [];
while ((el = els.iterateNext())) {
// save results to avoid mutation error
results.push(el);
}
results[0].x.baseVal.value = 50;
results[0].setAttribute('stroke', 'orange');
results[0].setAttribute('stroke-width', 2);
Now that IE 11 is almost dead… we can use document.evaluate
– I knew there would be some trick to get it to work on svg… Found the answer from user Martin Honnen on stackoverflow – very cool.
Of course this one can be done with document.querySelectorAll('*[fill="blue"]')
– but xPath can do some other stuff that css selectors can’t exactly do yet…