Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traversing to a specific child element with Prototype

Given the following markup.

<div id="example">
  <div>
    <div>
      <input type='hidden'></input>
    </div>
  </div>
</div>

How can I quickly get the hidden input element given I have the ID for the top most div element with the ID 'example'?

I can hack away at it so I can just iterate through each child element until I hit the input, however, I'd like to improve on that and utilize Prototype and simply jump to that hidden input given the div.

Thanks!

like image 457
mwilliams Avatar asked Aug 14 '09 14:08

mwilliams


2 Answers

Prototype provides a whole bunch of ways to do this:

// This, from Bill's answer, is probably the fastest, since it uses the 
// Browser's optimized selector engine to get straight to the element
$$('#example input[type=hidden]').first();

// This isn't bad either. You still use the browser's selector engine 
// To get straight to the #example element, then you must traverse a 
// (small) DOM tree.
// 
// element.down(selector) selects the first node matching the selector which 
// is an decendent of element
$('example').down('input');

// Here, you'll get an array containing all the inputs under 'example'. In your HTML
// there is only one. 
$('example').select('input')

// You can also use element.select() to combine separate groups of elements,
// For instance, if you needed all the form elements:
$('example').select('input', 'textarea', 'select');
like image 176
Kenan Banks Avatar answered Nov 15 '22 05:11

Kenan Banks


$$('#example input[type=hidden]').first()
like image 29
Bill Burcham Avatar answered Nov 15 '22 04:11

Bill Burcham