首页 > jQuery中的siblings()效果,用javascript如何实现

jQuery中的siblings()效果,用javascript如何实现

如何用javascript实现jQuery中siblings()的效果


var a = document.querySelector("li"),
    siblings = function( n, elem ) {
        var matched = [];

        for ( ; n; n = n.nextSibling ) {
            if ( n.nodeType === 1 && n !== elem ) {
                matched.push( n );
            }
        }

        return matched;
    },
    brother = siblings( a.parentNode.firstChild , a );
    
console.info( brother )

siblings()是jQuery源码


JSLite 中 $(select).siblings 实现看起来要比 jQuery 源码容易懂一点


javaScript,有nextSibling,previousSibling,找下一个节点,上一个节点。nextElementSibling,previousElementSibling,找下一个元素节点,上一个元素节点。n如果你要获取所有的siblings,那么就遍历。
比如ul下的li

var get_ul = document.querySelector('ul'),
    get_lis = get_ul.getElementsByTagName('li'),
    sib_eles = [];

var getSiblings = function(element) {
    for(var i=0;i<get_lis.length;++i) {
        if(get_lis[i] === element) {
            continue;
        }
        sib_eles.push(get_lis[i]);
    }
    return sib_eles;
}
   

        var third = document.querySelectorAll('.third')[0];
        
        function siblings(elem){
            var ret = [],
                elem = elem.nextSibling;
                
            for(; elem; elem = elem.nextSibling){
                if(elem.nodeType == 1){
                    ret.push(elem);
                }
            }
            return ret;
        }
        console.log(siblings(third));
【热门文章】
【热门文章】