Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery-not in pure JavaScript

How can I write the following jQuery-not…

$(".hover").not(".selected");

… in pure JavaScript?

like image 903
albuvee Avatar asked Nov 08 '10 09:11

albuvee


2 Answers

allItems = document.getElementsByTagName('*');
goodItems = [];
for(i=0;i<allItems.length;i++){
    if(
        allItems[i].className && 
        (' '+allItems[i].className.replace(/\s+/g, ' ')+' ').indexOf(' '+'hover'+' ') != -1 && 
        (' '+allItems[i].className.replace(/\s+/g, ' ')+' ').indexOf(' '+'selected'+' ') == -1
    )
        goodItems.push(allItems[i]);
}

If you need these kind of class selections often you should consider saving them as functions or even replicating some of the jQuery behaviour to be able to do stuff like $(".hover").not(".selected");

like image 63
Alin Purcaru Avatar answered Oct 31 '22 19:10

Alin Purcaru


The following will work. It could be optimized by using a native browser implementation of getElementsByClassName() where present to filter the list to just elements with the "hover" class.

function hasClass(el, cssClass) {
    return el.className && new RegExp("(^|\\s)" + cssClass + "(\\s|$)").test(el.className);
}

var matchingElements = [];
var allElements = document.getElementsByTagName("*");
for (var i = 0, len = allElements.length, el; i < len; ++i) {
    el = allElements[i];
    if (hasClass(el, "hover") && !hasClass(el, "selected")) {
        matchingElements.push(el);
    }
}
like image 44
Tim Down Avatar answered Oct 31 '22 19:10

Tim Down