Patrick
Patrick

Reputation: 92520

Getting closest element by id

I have two elements:

<input a>
<input b onclick="...">

When b is clicked, I want to access a and manipulate some of its data. A does not have a globally unique name, so document.getElementsByName is out. Looking into the event object, I thought event.target.parentNode would have some function like getElementsByName, but this does not seem to be the case with <td>s. Is there any simple way to do this?

Upvotes: 0

Views: 2341

Answers (4)

17 of 26
17 of 26

Reputation: 27382

If a and b are next to each other and have the same parent, you can use the prevSibling property of b to find a.

Upvotes: 5

ujh
ujh

Reputation: 4083

Prototype also has nice functions to move around in the DOM. In your example something like the following would do the trick:

b.up().down('a')

And if there are is more than one a element at that level you have the power of CSS selectors at your hand to specify exactly which element you want

Upvotes: 1

rp.
rp.

Reputation: 17683

Leave your plain vanilla JavaScript behind. Get JQuery--it will save you a ton of time.

http://docs.jquery.com/Selectors

Upvotes: -1

Joseph Pecoraro
Joseph Pecoraro

Reputation: 2876

  1. You should be able to find the element that was clicked from the event object. Depending on your browser you might want e.target or e.srcElement. The code below is from this w3schools example:

    function whichElement(e) {
      var targ;
      if (!e) var e = window.event;
      if (e.target) {
        targ=e.target;
      } else if (e.srcElement) {
        targ = e.srcElement;
      }
    
      if (targ.nodeType==3) { // defeat Safari bug 
        targ = targ.parentNode;
      }
    
      var tname;
      tname = targ.tagName;
      alert("You clicked on a " + tname + " element.");
    }
    
  2. You may then use the nextSibling and prevSibling DOM traversal functions. Some more information here. And yet again a w3schools reference for XML DOM Nodes.

Upvotes: 2

Related Questions