2009-08-14 11 views
9

Z uwzględnieniem następującego znacznika.Przechodzenie do określonego elementu podrzędnego z prototypem

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

W jaki sposób mogę szybko uzyskać ukryty element wejściowy, biorąc pod uwagę, że mam identyfikator dla najwyższego elementu div z identyfikatorem "przykład"?

Potrafię się z tego wyłamać, więc mogę po prostu przejrzeć każdy element potomny, dopóki nie uderzę w dane wejściowe, jednak chciałbym poprawić to i użyć prototypu i po prostu przeskoczyć do ukrytego wejścia podanego jako div.

Dzięki!

Odpowiedz

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

Dzięki! Wiedziałem, że to jest proste (i robi to całkiem sensownie patrząc na to). Naprawdę potrzebuję przyspieszyć pracę z JS i znaleźć to, czego potrzebuję w dokumentach. – mwilliams

+0

To za pomocą jQuery. Jak szybko uzyskać to za pomocą normalnego javascript? – Sriram

+0

Jak to zrobić, gdy 'przyklad' jest klasą, a nie identyfikatorem? – Sliq

26

Prototype dostarcza całą masę sposobów, aby to zrobić:

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

Wolę bezpośrednie podejście

document.forms[0].fieldName.value 

który jest mniej kodu, bez potrzeby korzystania z jQuery i jest bardziej przyjazny dla projektowania kodu.

Powiązane problemy