I have the coordinates (X,Y) of a point in an HTML document. How do I determine what DOM node is at those coordinates?
Some ideas:
(Background: I'm embedding Qt's QWebView in a native application. I'm trying to vary the context menu that the Qt widget provides based on the DOM node that the mouse is over, but Qt 4.5 cannot hit test to a DOM element, though that functionality is coming in 4.6. So I'm hoping I can toss the the coordinate into Javascript and do the hit testing there with DOM APIs.)
Thanks!
The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object. In the Console, get the element and assign it to the demoId variable. Logging demoId to the console will return our entire HTML element.
# Search for nodes You can search the DOM Tree by string, CSS selector, or XPath selector. Focus your cursor on the Elements panel. Press Control + F or Command + F (Mac). The Search bar opens at the bottom of the DOM Tree.
The most common methods for selecting/creating a list of nodes in an HTML document are: querySelectorAll() getElementsByTagName() getElementsByClassName()
The DOM Node interface is an abstract base class upon which many other DOM API objects are based, thus letting those object types to be used similarly and often interchangeably. As an abstract class, there is no such thing as a plain Node object.
As long as your users aren't using old versions of Safari, Chrome or Opera, you're in luck: use document.elementFromPoint(x, y)
(MSDN ref, Mozilla ref, QuirksMode article):
Returns the element from the document ... which is the topmost element which lies under the given point.
If you need to support older browsers, I can't think of many options other than what you suggest (traverse the entire DOM, looking at element positions and sizes and seeing if any of them encapsulate your (x, y)).
I don't think the event simulation will work but it is an interesting idea. My understanding of event dispatching is you specify the target that the event is for, which is precisely what you are trying to find out in the first place.
document.elementFromPoint(x,y)
Documented here for Firefox 3 and here for IE, but see quirksmode for cross-browser differences.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With