Posted By

troynt on 02/07/09


Tagged

XPath


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

enajenkins


CSS2XPATH


 / Published in: JavaScript
 

only handles child selectors, classnames and IDs

I didn't write this, nor have I tested it. Saving it just in case I need it.

  1. // only handles child selectors, classnames and IDs
  2. function css2xpath(css) {
  3. var fragments = css.split(/\s+/), xpath = ['.'], child = false
  4.  
  5. xpath.add = function(part) {
  6. xpath.push(child ? '/' : '//')
  7. child = false
  8. xpath.push(part || '*')
  9. }
  10.  
  11. fragments.forEach(function(fragment) {
  12. if (!fragment) return;
  13. if (fragment == '>') child = true;
  14. else if (/^([^.]*)\.([\w.-]+)$/.test(fragment)) {
  15. xpath.add(RegExp.$1)
  16. RegExp.$2.split('.').forEach(function(className) {
  17. xpath.push(xpathClass(className))
  18. })
  19. }
  20. else if (/^([^.]*)#([\w-]+)$/.test(fragment)) {
  21. xpath.add(RegExp.$1)
  22. xpath.push('[@id="' + RegExp.$2 + '"]')
  23. }
  24. else xpath.add(fragment)
  25. })
  26. return xpath.join('')
  27. }

Report this snippet  

You need to login to post a comment.