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
.
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.
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.
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.
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';
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With