2009-08-14 11 views
9

Dada la siguiente marca.Atravesando un elemento hijo específico con Prototype

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

¿Cómo puedo obtener rápidamente el elemento de entrada oculta dado que tengo el ID de la parte superior más div elemento con el ID 'ejemplo'?

Puedo hackearlo así que puedo iterar a través de cada elemento secundario hasta que toco la entrada, sin embargo, me gustaría mejorarlo y utilizar Prototype y simplemente saltar a esa entrada oculta dado el div.

Gracias!

Respuesta

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

Gracias! Sabía que era simple (y tiene todo el sentido mirarlo). Realmente necesito ponerme al día con JS y encontrar lo que necesito en los documentos. – mwilliams

+0

Esto mediante el uso de jQuery. ¿Qué le parece conseguirlo rápidamente usando javascript normal? – Sriram

+0

¿Cómo hacer esto cuando 'example' es una clase, no una identificación? – Sliq

26

Prototype ofrece un montón de maneras de hacer esto:

// 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

Yo prefiero el enfoque directo

document.forms[0].fieldName.value 

que es menos código, sin necesidad de utilizar jQuery y es más amigable con el diseño de código.

Cuestiones relacionadas