• Notice regarding image hosts and attachments. See here.

JS prototype get class within known element

Associate
Joined
26 Nov 2004
Posts
1,480
Location
Gran Canaria
Hi

Can someone please answer me a quick question which is taking too long to find on the net.

With prototype I can find elements easily by className or id but how do i find an element within a know element.

eg

$$(".someClass").each(function(elmt) { });

where I want to find elements of classname 'someClass' within an element already stored.

Many thanks in advance.
 
I don't use Prototype, but the docs suggest: http://www.prototypejs.org/api/element/select
Code:
var selectedChildren = $('apples').select('.someClass');
or if the parent element is already in a var:
Code:
var parentElement = $('apples');
var selectedChildren = parentElement.select('.someClass');
or use a child selector for immediate children:
Code:
var selectedChildren = $$('#apples > .someClass');
or use a descendant selector for all children:
Code:
var selectedChildren = $$('#apples .someClass');
 
No problem. Admittedly, even though I had a good idea of what I was looking for, it wasn't easy to find in the manual :D. It's not the most intuitive of documentation, and I recall it being much more clear at one point.
 
I generally have a terrible time with api's if i'm honest, probably due to my lack of patience. :(

One more question. If I have an js object, how can i get the first element of it without using a for in loop.

eg

obj['some1']['some2']

How can i get 'some1' returned without using for .. in? I'm guessing it's possible but realise javascript is limited compared with other languages.

Thanks again.
 
Depends exactly what you mean by 'object' - there are native Objects and native Array objects. And even then, some js frameworks have a concept of 'objects', but they're accessible as arrays. A problem of loose typing.

If your "obj" acts as, or is, an array, you can reference by index. So first element of obj['some1'] can be retrieved with obj['some1'][0] and first element of obj with obj[0].
 
Thanks for reply.

I'm referring to a data object, which to my understanding is actually an array in javascript. What you describe, obj[0] is pretty much exactly what I am looking for but it seems not to work, unless i'm doing something wrong.
 
Another problem I'm having..

Code:
	$('sidebar').select($$('div')).each(function(me){me.remove()})

This is removing anything within the sidebar, instead of just div's.

Help's appreciated. :)
 
Back
Top Bottom