Hide an element's next sibling with Javascript

2019-01-18 04:20发布

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:

elem.nextSibling.style.display = 'none';

Firebug error was elem.nextSibling.style is undefined.

4条回答
欢心
2楼-- · 2019-01-18 05:00

Try looping through the children of this element using something like:

var i=0;
(foreach child in elem)
{
   if (i==0)
   {
     document.getElementByID(child.id).style.display='none';
    }
}

Please make appropriate corrections to the syntax.

查看更多
疯言疯语
3楼-- · 2019-01-18 05:06

Take a look at the Element Traversal API, that API moves between Element nodes only. This Allows the following:

elem.nextElementSibling.style.display = 'none';

And thus avoids the problem inherent in nextSibling of potentially getting non-Element nodes (e.g. TextNode holding whitespace)

查看更多
爷的心禁止访问
4楼-- · 2019-01-18 05:08

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';
查看更多
beautiful°
5楼-- · 2019-01-18 05:09

Firebug error was elem.nextSibling.style is undefined.

because nextSibling can be a text-node or other node type

do {
   elem = elem.nextSibling;
} while(element && elem.nodeType !== 1); // 1 == Node.ELEMENT_NODE
if(elem) elem.style.display = 'none';
查看更多
登录 后发表回答