<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 the 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 the next node correctly
var nodeId=document.getElementById(node[0]); //for the first
//iteration i get the row in
//nodeId correctly but for the next iterations, i get null,
//althought the row exists. if i type in the row Id manually
//it works, but if i use node[0] then it returns null !! :S
alert("the node is : " + 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 all i dint know how to run the above code on Jsfiddle and then link it to my question. sorry for that!!
In executeFunc() in javascript, i am spliting the cookie entries and extracting the names in “node” variable. then using this name, i get the row object and print it. when it loops for the first time, everything goes as planned but for the next iterations, alert(node[0]) prints the next entry in the cookie(i.e node-2) but nodeId=document.getElementById(node[0]) returns null. if i change it to nodeId=document.getElementById("node-2") it works fine. i dont knw wat the prblm is..you can test it by just copy pasting it…its the complete code!!
Thanks!!
Your cookie has a space in front of each identifier. Thus, it tries to look up
" node-1"and doesn’t find it. You can see the spaces in this version of your code with quote marks around the alert text: http://jsfiddle.net/jfriend00/ZS3HB/.I’d suggest either revising the split to
split('; ')or trim leading/trailing spaces off the identifiers before using them.