xPath contains (document.evaulate)
copy // hack to shove some html on the page since snippet.zone // quick editor does not yet support HTML :P document.body .innerHTML += ` < p> This is some text to search...</ p> < p> Here are some random words "Robot, Cat, Swan, Shadow" ...</ p> < button> Say Hello Robot</ button> `; /////////// // find elements with the word `search` let els = document.evaluate ( "//p[contains(., 'search')]" , document, null , XPathResult.ANY_TYPE , null ) ; let el; while ( el = els.iterateNext ( ) ) { console.log ( 'match "search"' , el) ; } els = document.evaluate ( "//body/*[contains(., 'Robot')]" , document, null , XPathResult.ANY_TYPE , null ) ; while ( el = els.iterateNext ( ) ) { console.log ( 'match "Robot"' , el) ; }
Try it out…
Now that IE is almost dead… we can use xPath – take a look at your console
xPath and svg
copy // 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 ) ;
Try it out…
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…