Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide an element's next sibling with Javascript

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.

like image 669
DisgruntledGoat Avatar asked May 15 '09 12:05

DisgruntledGoat


People also ask

What is next element sibling in Javascript?

The Element. nextElementSibling read-only property returns the element immediately following the specified one in its parent's children list, or null if the specified element is the last one in the list.

How can I get next sibling in jQuery?

jQuery next() Method The next() method returns the next sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse forward along the next sibling of DOM elements.

What is the nextSibling Is it a Javascript command what is its purpose?

The nextSibling property is used to return the next node of the specified node as Node object or null if the specified node is the last one in the list. It is a read-only property. Return value: This property returns a next sibling of the specified node or null if the current node has no next sibling.


2 Answers

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';
like image 55
Russ Cam Avatar answered Sep 20 '22 13:09

Russ Cam


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)

like image 29
cobaco Avatar answered Sep 16 '22 13:09

cobaco