Hide an element's next sibling with Javascript

前端 未结 4 1550
天命终不由人
天命终不由人 2020-12-09 04:23

I have an element grabbed from document.getElementById(\'the_id\'). How can I get its next sibling and hide it? I tried this but it didn\'t work:



        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 05:04

    it's because Firefox considers the whitespace between element nodes to be text nodes (whereas IE does not) and therefore using .nextSibling on an element gets that text node in Firefox.

    It's useful to have a function to use to get the next element node. Something like this

    /* 
       Credit to John Resig for this function 
       taken from Pro JavaScript techniques 
    */
    function next(elem) {
        do {
            elem = elem.nextSibling;
        } while (elem && elem.nodeType !== 1);
        return elem;        
    }
    

    then you can do

    var elem = document.getElementById('the_id');
    var nextElem = next(elem); 
    
    if (nextElem) 
        nextElem.style.display = 'none';
    

提交回复
热议问题