...

View Full Version : Resolved nextSibling not working.



ubh
09-25-2008, 05:37 AM
Why wont this work?



var getNextSibling = document.getElementById("someElement").nextSibling;
if (getNextSibling = null)
{
alert("SORRY NO SIBLINGS");
}
else
{
alert(getNextSibling);
}

abduraooft
09-25-2008, 06:57 AM
if (getNextSibling = null) because you're assigning(=) null to the variable!

Kor
09-25-2008, 03:33 PM
Why wont this work?



var getNextSibling = document.getElementById("someElement").nextSibling;
if (getNextSibling = null)
{
alert("SORRY NO SIBLINGS");
}
else
{
alert(getNextSibling);
}

It depends on what do you mean by nextSibling. An element Node (an HTML tag), a text Node, a comment Node...?

Whenever you are searching for siblings you must specify the type of the element you are looking for (the nodeType)

See also:
http://developer.mozilla.org/en/DOM/element.nodeType

You must also keep in mind that browsers count the childnodes (thus they refere the siblings) in different ways. For instance, Mozilla counts as childNodes (and siblings) all the possible text nodes (the empty sapces between tags, the "gaps"), while IE counts only some of them. This is another reason for a nodeType test is required, combined with a while loop



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/javascript">
function findNextSib(){
var e=document.getElementById('myDiv'), nextS=e.nextSibling;
while(nextS.nodeType!=3){
nextS=nextS.nextSibling;
}
alert('the next text Node is: '+nextS.nodeValue);
nextS=e.nextSibling;
while(nextS.nodeType!=8){
nextS=nextS.nextSibling;
}
alert('the next comment Node is: '+nextS.nodeValue);
nextS=e.nextSibling;
while(nextS.nodeType!=1){
nextS=nextS.nextSibling;
}
alert('the next tag Node is: an element with the id='+nextS.id)
}
onload=findNextSib;
</script>
</head>
<body>
<div>
<div id="myDiv"></div>
nextSibling text
<!--nextSibling comment-->
<div id="nextSiblingTag"></div>
</div>
</body>
</html>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum