views:

13

answers:

2

Hi, i have created a script to associate data to dom nodes, something like the jQuery.data method. Basically the script sets a property on the node that is the key of an object that will contain the data of every node, but in IE 7 setting a property on a text node throws an error:

var a=document.createElement("div");
a.test="test";
alert(a.test); //Works and shows "test"

var a=document.createTextNode("text");
a.test="test";  //Throws an error

So do you know a workaround for this bug? Or maybe is there a property that is almost useless on text nodes that allows me to set data on it?

A: 

I believe that this is because createTextNode makes straight text as opposed to an element. Therefore, you cannot assign properties to it.

I would try doing createElement("p") (or any element type) if you want to show text.

EDIT: This is incorrect. See Tim Down's answer for the solution.

huntaub
No. `document.createTextNode` creates a text node, as strongly hinted at by its name.
Tim Down
createTextNode generates a text node not simply a text and my question is not about showing text i'm looking for a way to assign a property on it
mck89
Whoopsie. Sorry about that.
huntaub
+2  A: 

Best plan: don't do this.

In general, it's a bad idea to assign properties to a host object (i.e. anything provided by the browser rather than native JavaScript objects). Host objects are not obliged to allow this kind of extension (a.k.a. "expandos") and many (for example, ActiveX objects in IE) do not. Furthermore, IE allows you to prevent expandos on all DOM nodes within a document by using document.expando = false;.

One alternative would be to use jshashtable to store data for text nodes. It's a hash table implementation that allows you to use any object (not just strings) as a key.

Tim Down
Yeah i agree with you but that is the only (safe) way to link elements to data. So there's no way to do that on text nodes right?
mck89
Added a suggested alternative.
Tim Down
Yeah with jshashtable it works now i have to understand how. Thanks!!!
mck89
Internally, jshashtable is storing a set of arrays ("buckets"). All the text nodes will go in the same array. Each entry in this array is an object containing the key (the text node) and the value (your piece of data). When you call `get()` with a particular text node, it simply searches through the array until it finds an entry whose `key` property is the text node and returns that entry's `value` property.
Tim Down