)
}
}
)
(
}
{
)
)
(
)
(
(
{
}
)
(
)
}
)
)
{
(
(
)
)
}
)
(
}

xPath and svg

  1. // hack to shove some html on the page since snippet.zone
  2. // quick editor does not yet suppor HTML :P
  3. document.body.innerHTML += `
  4.   <svg style="overflow:visible">
  5.   <rect x="10" y="10" fill="red" width="30" height="10" />
  6.   <rect x="10" y="20" fill="blue" width="30" height="10" />
  7.   <rect x="10" y="30" fill="purple" width="30" height="10" />
  8.   </svg>
  9. `;
  10.  
  11. const svgPrefix = pre => pre === 'svg' && 'http://www.w3.org/2000/svg';
  12.  
  13. // https://stackoverflow.com/questions/31162358/extract-svg-element-by-using-document-evaluate
  14. let els = document.evaluate(
  15.   '//svg:svg/*[@fill="blue"]',
  16.   document,
  17.   svgPrefix,
  18.   XPathResult.ANY_TYPE,
  19.   null
  20. );
  21.  
  22. const results = [];
  23. while ((el = els.iterateNext())) {
  24.   // save results to avoid mutation error
  25.   results.push(el);
  26. }
  27. results[0].x.baseVal.value = 50;
  28. results[0].setAttribute('stroke', 'orange');
  29. 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…

// svg // xPath
snippet.zone ~ 2021-24 /// {s/z}