Posted By

brianyang on 06/09/10


Tagged


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

o0110o


Get Elements By CSS Selector


 / Published in: JavaScript
 

  1. function $$(xpath,root) {
  2. xpath = xpath
  3. .replace(/((^|\|)\s*)([^/|\s]+)/g,'$2.//$3')
  4. .replace(/\.([\w-]+)(?!([^\]]*]))/g, '[@class="$1" or @class$=" $1" or @class^="$1 " or @class~=" $1 "]')
  5. .replace(/#([\w-]+)/g, '[@id="$1"]')
  6. .replace(/\/\[/g,'/*[');
  7. str = '(@\\w+|"[^"]*"|\'[^\']*\')';
  8. xpath = xpath
  9. .replace(new RegExp(str+'\\s*~=\\s*'+str,'g'), 'contains($1,$2)')
  10. .replace(new RegExp(str+'\\s*\\^=\\s*'+str,'g'), 'starts-with($1,$2)')
  11. .replace(new RegExp(str+'\\s*\\$=\\s*'+str,'g'), 'substring($1,string-length($1)-string-length($2)+1)=$2');
  12. var got = document.evaluate(xpath, root||document, null, 5, null);
  13. var result=[];
  14. while (next = got.iterateNext())
  15. result.push(next);
  16. return result;
  17. }
  18.  
  19.  
  20.  
  21. // Example usage:
  22.  
  23. $$('#title')[0].innerHTML='Greased';
  24.  
  25. $$('a[@href $= "user.js"]').forEach(function (a) {
  26. a.innerHTML='check it out a script';
  27. });
  28.  
  29. $$('a[@href ^= "http"]').forEach(function (a) {
  30. a.innerHTML += ' (external)';
  31. });

Report this snippet  

You need to login to post a comment.