views:

238

answers:

4

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?

+4  A: 

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'.

17 of 26
+2  A: 
  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.

Joseph Pecoraro
+1  A: 

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

http://docs.jquery.com/Selectors

rp
+1  A: 

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

ujh