Created
September 14, 2014 06:09
-
-
Save mubaidr/218e45aa83d2005bfc15 to your computer and use it in GitHub Desktop.
A small snippet to select element sin JavaScript using CSS selector syntax.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment