Traversing to a specific child element with Prototype

mwilliams picture mwilliams · Aug 14, 2009 · Viewed 22.1k times · Source

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!

Answer

Triptych picture Triptych · Aug 14, 2009

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');