views:

53

answers:

4

I'm using prototype and have some divs with id p1 p2 p3... In these divs I have some divs with id d1 d2 d3...

I would like to use $ to get the specified d element, in the specified p element.

If I'm given the values 3 and 4 I should be able to go $('p3').$('d4') This syntax doesn't work of course.

There's an easy way to do this with jQuery so I'm assuming this exists in prototype

+1  A: 

Considering an id ("identifier") is (should be) unique, why not just use the most specific identifier you have -- the second one :

$('d4')

If your identifiers are not unique, they are not identifiers... And they shouldn't be used as the "id" attribute of your divs...


Actually, if you have something like this :

p1
  d1
  d2
p2
  d1
  d2
  d3
p3
  d1

Your "pX" can be id (they are unique), but your "dX" shouldn't be ids ; a solution might be to use the class to store the "dX" information.

A bit like this, I suppose :

id=p1
  class=d1
  class=d2
id=p2
  class=d1
  class=d2
  class=d3
id=p3
  class=d1

Then, you'll use the $$ function with a CSS-selector : if you want the element with a class="d2" inside the elemnt of id="p1", something like this might work :

$$('#p1 .d2');

ie :

  • #p1 = element with id=p1
  • .d2 = element which has a class containing d2


Hope this is clear and helps...

Pascal MARTIN
+1  A: 

This ought to work:

$('p3').select('#d4').first()

Then again, if all of your ids are unique, as they should be, why not just do this:

$('d4');
Triptych
+2  A: 

Unfortunately, prototype's $ function doesn't chain, as it returns an extended HTMLElement object and $ is a window method. However, you could use the $$ function along with a CSS selector to achieve this:

$$('#p3 #d4').first(); // Element with id 'd4' that's a descendant of an element with id 'p3'

While the $$ function returns an extended HTMLElement object just like $, it actually returns an array of them, as a CSS selector could potentially match multiple elements.

You can read about CSS selectors here.

Daniel Vandersluis
+1. Although it should still be mentioned that it's generally better to just do $('d4'), which is equivalent to your example.
Triptych
Agreed. My approach here just enforces the p3->d4 relationship from the question, but as other answers have pointed out, IDs should be singular, in which case $('d4') would be adequate.
Daniel Vandersluis
A: 
$('p3').select(new Selector('#d4'));
chaos