使用Prototype遍历特定的子元素

mwi*_*ams 9 javascript prototypejs

鉴于以下标记.

<div id="example">
  <div>
    <div>
      <input type='hidden'></input>
    </div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

如果我拥有ID为'example'的最顶部div元素的ID,我如何快速获取隐藏的输入元素?

我可以破解它,所以我可以遍历每个子元素直到我点击输入,但是,我想改进它并利用Prototype并简单地跳转到给定div的隐藏输入.

谢谢!

Tri*_*ych 27

Prototype提供了许多方法来执行此操作:

// 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');
Run Code Online (Sandbox Code Playgroud)


Bil*_*ham 16

$$('#example input[type=hidden]').first()
Run Code Online (Sandbox Code Playgroud)