开发者

jQuery-not in pure JavaScript

How can I write t开发者_如何学编程he 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);
    }
}


You can also use following function to get elements by class name.

excludeClass is an optional parameter here, this function will still work if you only define the includeClass parameter.

function getElementsByClassName(includeClass, excludeClass) {
    var elements = []; var el = document.getElementsByTagName('*');
    var regexp1 = new RegExp("\\b" + includeClass + "\\b");
    var regexp2 = new RegExp("\\b" + (excludeClass ? excludeClass : "") + "\\b");
    for (var i = 0; i < el.length; i++) {
        if (regexp1.test(el[i].className) && !regexp2.test(el[i].className)) { elements.push(el[i]); }
    }
    return elements;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜