I want to store elements as the keys in my array and object as values,for example -
var arr = [];
arr[ document.getElementById('something') ] = { data: 'something' , fn : function(){ } };
But the problem is: If I will add another element with the key of : document.getElementById('otherthing').
And later will try to get the value of : arr[ document.getElementById('something') ].data , I will get the value of arr[ document.getElementById('otherthing') ].
For Example :
var arr = [];
arr[ document.getElementById('something') ] = { data: 'something' , fn : function(){ } };
arr[ document.getElementById('otherthing') ] = { data: 'otherthing' , fn : function(){ alert('k'); } };
alert( arr[ document.getElementById('otherthing') ].data ); // alerts "otherthing"
alert( arr[ document.getElementById('something') ].data ); // alerts "otherthing" but suppose to alert "something"
How I can fix this problem,I can`t save by id,because I want to support other nodes with no-id
Thanks,Yosy.
EDIT:My answer to this,If you have better answer please write it :) (Inspired by casablanca`s answer)
array for id: key-integer the node id, value the node it self
and the array with data and fn with key of my id,It will look like this :
var idArray = [],nodeArray = [];
idArray[0] = document.getElementById('hello_ducks');
nodeArray[0] = { data: 'hello ducks!!' , fn : function(){ alert('k'); } };
idArray[1] = document.getElementById('hello');
nodeArray[1] = { data: 'hello' , fn : function(){ } };
var testNode = document.getElementById('hello_ducks'), foundId = -1 /*found id*/;
// Do we have testNode in our array?
for(var i = 0 ; i < idArray.length; i++ ){
if( idArray[i] === testNode ){
foundId = i;
}
}
// Do we found our element?
if(foundId >= 0) {
alert( nodeArray[foundId].data ); // "hello ducks!!"
}
.datamethod, that may be what you want. api.jquery.com/data