2009-08-14 53 views
9

给定以下标记。使用原型遍历到特定的子元素

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

我如何快速得到隐藏的输入元素给定ID为'example'的顶部div元素ID?

我可以破解它,所以我可以迭代通过每个子元素,直到我点击输入,但是,我想改善这一点,并利用原型,并简单地跳转到给定div的隐藏输入。

谢谢!

回答

16
$$('#example input[type=hidden]').first() 
+0

谢谢!我知道这很简单(并且看起来完全有意义)。我真的需要加快JS的速度,并找到我需要的文档。 – mwilliams 2009-08-14 14:59:20

+0

这通过使用jQuery。如何快速获得它使用正常的JavaScript? – Sriram 2012-06-15 11:51:15

+0

当'example'是一个类,而不是一个id时如何做到这一点? – Sliq 2013-05-10 13:16:56

26

原型提供了一大堆的方法可以做到这一点:

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

我更喜欢直接的方式

document.forms[0].fieldName.value 

这是更少的代码,无需使用jQuery和更友好的代码设计。