Patrick Patrick - 6 months ago 20
HTML Question

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?

Answer

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.