Getting closest element by id
-
09-06-2019 - |
Question
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?
Solution
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
.
OTHER TIPS
You should be able to find the element that was clicked from the event object. Depending on your browser you might want
e.target
ore.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."); }
You may then use the
nextSibling
andprevSibling
DOM traversal functions. Some more information here. And yet again a w3schools reference for XML DOM Nodes.
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
Leave your plain vanilla JavaScript behind. Get JQuery--it will save you a ton of time.