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

xPath contains (document.evaulate)

  1. // hack to shove some html on the page since snippet.zone
  2. // quick editor does not yet support HTML :P
  3. document.body.innerHTML += `
  4.   <p>This is some text to search...</p>
  5.   <p>Here are some random words "Robot, Cat, Swan, Shadow"...</p>
  6.   <button>Say Hello Robot</button>
  7. `;
  8.  
  9. ///////////
  10.  
  11. // find elements with the word `search`
  12. let els = document.evaluate(
  13.   "//p[contains(., 'search')]",
  14.   document,
  15.   null,
  16.   XPathResult.ANY_TYPE,
  17.   null
  18. );
  19. let el;
  20. while (el = els.iterateNext()) {
  21.   console.log('match "search"', el);
  22. }
  23.  
  24. els = document.evaluate(
  25.   "//body/*[contains(., 'Robot')]",
  26.   document,
  27.   null,
  28.   XPathResult.ANY_TYPE,
  29.   null
  30. );
  31. while (el = els.iterateNext()) {
  32.   console.log('match "Robot"', el);
  33. }

Now that IE is almost dead… we can use xPath – take a look at your console

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}