开发者

How to identify HTML elements (in javascript) in a browser agnostic fashion

开发者 https://www.devze.com 2022-12-23 15:59 出处:网络
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 开发者_如何学Cthe page.I need to record which element w

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 开发者_如何学Cthe 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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号