tags:

views:

154

answers:

2

Hi All,

I need to identify all html elements on a page in a browser agnostic fashion. What I am basically doing is using mouse events to record clicks on the page. I need to record which element was clicked. So I add a mouse down listener to the document.body element. And on mouse down I get the element under the mouse. Lets say its a div. I then use the index of that div inside the document.getElementsByTagName('*') nodelist and the nodeName ('div') to identify that div. A sample element id would be div45 which means its a div and its the 45th element in the '*' nodelist.

This is all fine and good until I use IE which gives me different indexes. So div45 in FireFox may be div47 in IE.

Anyone have any ideas? I just need the id of all elements on the page to be the same in any browser, perhaps indexing is not good enough but I really don't have any more ideas.

Thanks

Guido

+1  A: 

IE incorrectly returns comment nodes as part of getElementsByTagName('*'). Filter those out (e.g. by collecting Element nodes only — node.nodeType === 1) and you should have a consistent result.

kangax
Great stuff, this passes all my tests in all browsers! Great to have an intelligent explanation for this also.
gatapia
+2  A: 

Javascript libraries like jQuery are designed to be browser-agnostic. Please use them.

Searching through the whole DOM tree does not seem good approach to me.

N 1.1
Unfortunatelly I cannot use a library in my script (complex reasons). However I could rip out identitification code of an MIT licensed project like jQuery. However I don't think jQuery IDs elements does it? I know it adds silly jQueryxxxx attributes to input tags but thats not really what I need.
gatapia
@gatapia, do you want a naming convention for identifying the elements ? or a reference to the actual element ?
Gaby
@gatapia: what is that, you intend do _finally_ ? There must be a better/simpler way to do it.
N 1.1