strange behaviour of getElementById() and .split() method in Javascript -



strange behaviour of getElementById() and .split() method in Javascript -

<html> <script type="text/javascript"> function createcookie(name,value,days) { if (days) { var date = new date(); date.settime(date.gettime()+(days*24*60*60*1000)); var expires = "; expires="+date.togmtstring(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; }; function executefunc() { var cookiedata=document.cookie.split(';'); for(entry in cookiedata) { createcookie(cookiedata[entry],"",-1); //clear cookie first } createcookie("node-1","1",365); createcookie("node-2","1",365); createcookie("node-3","1",365); alert("the cookie contains : " + document.cookie); var cookie=document.cookie.split(';'); for(ele in cookie) { var node=cookie[ele].split('='); alert(node[0]); //this prints next node correctly var nodeid=document.getelementbyid(node[0]); //for first //iteration row in //nodeid correctly next iterations, null, //althought row exists. if type in row id manually //it works, if utilize node[0] returns null !! :s alert("the node : " + nodeid); alert(document.cookie); } } </script> <body onload="executefunc()"> <table> <tbody> <tr id="node-1"> <td>im node 1</td> </tr> <tr id="node-2"> <td>im node 2</td> </tr> <tr id="node-3"> <td>im node 3</td> </tr> </tbody> </table> </body> </html>

first of dint know how run above code on jsfiddle , link question. sorry that!!

in executefunc() in javascript, spliting cookie entries , extracting names in "node" variable. using name, row object , print it. when loops first time, goes planned next iterations, alert(node[0]) prints next entry in cookie(i.e node-2) nodeid=document.getelementbyid(node[0]) returns null. if alter nodeid=document.getelementbyid("node-2") works fine. dont knw wat prblm is..you can test re-create pasting it...its finish code!! thanks!!

your cookie has space in front end of each identifier. thus, tries " node-1" , doesn't find it. can see spaces in version of code quote marks around alert text: http://jsfiddle.net/jfriend00/zs3hb/.

i'd suggest either revising split split('; ') or trim leading/trailing spaces off identifiers before using them.

javascript

Comments

Popular posts from this blog

iphone - Dismissing a UIAlertView -

c# - Can ProtoBuf-Net deserialize to a flat class? -

javascript - Change element in each JQuery tab to dynamically generated colors -