How can I write the following jQuery-not…
$(".hover").not(".selected");
… in pure JavaScript?
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");
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With