4

I have a page that is open in two browser windows and which is communicating user interactions over sockets. If somebody clicks on an element I want it to happen in the other browser. For this I need to know the element that was interacted with.

I have a few options but none of them are 100% guaranteed to work.

  • by element name: there can be multiple elements with the same name.
  • by id: not all elements have an id
  • by class: not all elements have a class and classes aren't unique
  • by location: if the website is open in two different browsers the location can be different.

So is there an other way to identify elements that's 100% conclusive?

Pickels
  • 33,902
  • 26
  • 118
  • 178

1 Answers1

4

If you have the exact same HTML in both pages, you could simply use a "path" built with the index in parent up to document.body. It's easy to build and easy to use to find the element.

Here are functions to compute this path or follow it :

function indexInParent(node) {
    var children = node.parentNode.childNodes;
    for (var i=0; i<children.length; i++) {
         if (children[i]==node) return i;
    }
    return -1;
}

function nodePath(e) {
   var path = [];
   while (e!=document.body) {
      path.push(indexInParent(e));
      e = e.parentNode;
   }
   return path.reverse().join('-');
}

function getNode(path) {
   path = path.split('-');
   var e = document.body;
   while(path.length && e) e=e.childNodes[parseInt(path.shift())];
   return e;
}

Demonstration : click "Run with JS" then

  • click on an element to see the path in the console
  • type a path to see the element in the console
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • 1
    @Chris B here is a related question: http://stackoverflow.com/questions/5728558/jquery-get-the-dom-path-of-the-clicked-a If you search for 'find element by path' you find a lot of examples. – Pickels Apr 12 '13 at 14:00