Last active
August 29, 2015 14:02
-
-
Save Williammer/45180ebeb455552eb77a to your computer and use it in GitHub Desktop.
js2jQuery.queryClassWithRegexp.html - one example to find Class in selected elements with Regular expression. #note: 1. double escape slash "\\s" in RegExp constructor is just like the "\s" in literal regExp;
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
| <div class="samurai ninja"></div> | |
| <div class="ninja samurai"></div> | |
| <div></div> | |
| <span class="samurai ninja ronin"></span> | |
| <script> | |
| function findClassInElements(className, type) { | |
| var elems = document.getElementsByTagName(type || "*"); | |
| var regex = new RegExp("(^|\\s)" + className + "(\\s|$)"); // match either the beginning of a string or whitespace; adn class name; and the end of string... | |
| var results = []; | |
| for (var i = 0, length = elems.length; i < length; i++) | |
| if (regex.test(elems[i].className)) { | |
| results.push(elems[i]); | |
| } | |
| return results; | |
| } | |
| assert(findClassInElements("ninja", "div").length == 2, | |
| "The right amount of div ninjas was found."); | |
| assert(findClassInElements("ninja", "span").length == 1, | |
| "The right amount of span ninjas was found."); | |
| assert(findClassInElements("ninja").length == 3, | |
| "The right amount of ninjas was found."); | |
| </script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment