tags:

views:

21

answers:

1

If I only have a reference to document.getElementById('btn_test'), how can I get a reference to that first checkbox input element using only Javscript. Maybe a parent.parent? What is a safe way?

<td>
<input type="checkbox" name="text_rnd_input"/>
<label>
<button id="btn_test" type="button">
</button>
</label>
</td>
+4  A: 
btn_test.parentNode.parentNode.getElementsByTagName('input')[0]

Take care, if you use *Sibing properties, because they also select text nodes (for example, invisible ones with only whitespace) and are therefore usually not reliable with arbitrary HTML (think of compressing your HTML by removing whitespace).

And to stress the inevitable: With jQuery:

$btn_test.closest('td').children('input')[0]
// or
$btn_test.parent().prev('input')
// or ...
Boldewyn
+1 yup, just saw. Yours works: http://jsfiddle.net/gqcYC/
Pekka
I highly recommend jQuery for traversing the DOM. It makes it so much easier...
elusive