Williammer
6/17/2014 - 3:49 AM

js2jQuery.queryClassWithRegexp.html - one example to find Class in selected elements with Regular expression. #note: 1. double escape slash

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;

<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>