Wednesday, February 21, 2007

JAVASCRIPT: Associative Arrays

I've been programming in javascript for years. Sometimes I borrow other people's javascript code, other times I write my own. Whenever I borrow other people's code there often is a lot of browser independent stuff, like 'if (ie) or if (nn6)...' and I always wondered how they did it. I knew I could do this as well if I had a way to list all of a DHTML element's properties and functions. I could do this in different browsers and then learn when functions and properties to use in each browser.

Now I know how. Every HTML tag or page element can be accessed in javascript. Just tag your element with an id:
<div id='abc'></div>

to access the element, use this javascript
var element = document.getElementById('abc');

each object in javascript can have functions or properties, but all of these can be accessed as an associative array,
so to list all of the element's properties and functions you can do this:

var str = '';
for(var property in myObject) {
var value = myObject[property];
str+= "\n" + "myObject[" + property + "] = " + value;

You will notice a different set of properties displayed in IE, Safari, Firefox, etc.

No comments: