Hide an element's next sibling with Javascript
Asked Answered
T

4

15

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.

Tungting answered 15/5, 2009 at 12:28 Comment(0)
E
36

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';
Elisha answered 15/5, 2009 at 12:31 Comment(4)
But elem still might be null.Johannessen
No it doesn’t. It just guaratees that nextSibling is not accessed when elem is “not true” or elem.nodeType == 1. But if there isn’t such an element, elem is just the last sibling node regardless of what type it is.Johannessen
Here’s an example: var elem = document.createElement("div"); elem.appendChild(document.createTextNode("foo")); elem.appendChild(document.createTextNode("bar")); alert(next(elem.firstChild) === null); // "true"Johannessen
just wanted to confirm this is the another answer https://mcmap.net/q/757367/-hide-an-element-39-s-next-sibling-with-javascript but not in focus. Is anything wrong with it?Rommel
H
14

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)

Hypochondriasis answered 10/3, 2013 at 12:43 Comment(2)
i think this is the best and easiest way i dont understand why people didn't focused..Rommel
Works out if the box. Thanks.Hennery
C
2

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';
Counterstatement answered 15/5, 2009 at 12:32 Comment(1)
+1 For checking if elem is not null before accessing the style attribute.Johannessen
D
0

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.

Decahedron answered 15/5, 2009 at 12:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.