tags:

views:

59

answers:

2

Hi

I have the following code appearing multiple times on an html page (text values differ):

<div>
 <a href="1.html">
  <span class="e">
   <span class="1">stuff1</span>
   <span class="2">stuff2</span>
   <span class="3">stuff3</span>
  </span>
 </a>
 <a class="click" href="2.html">link</a>
</div>

what I'm trying to do is when the link "link" is clicked, spawn a dialog with values of stuff1, stuff2 and stuff3. I'm having trouble actually getting to the values of the spans. Effectively what I want is to take $(this) and get the text of it's sibbling's only span child's span children.

Thanks! -Mala

+3  A: 

I'm having a little trouble figuring out what you mean, but perhaps this is it:

$('.click').click(function() {
  // using our parent as a base, look for any class='e' element, and get its children.
  var $collection = $('.e > *', $(this).parent());
  var text = [];
  $collection.each(function() { 
    // add the text within each span to an array
    text.push($(this).text()); 
  });

  // show the text of the spans as a comma separated list
  alert(text.join(', '));


});

The .text() function on a jQuery object will return the text inside of a span (or any other element).

Response to comment:

$('.e span', $(this).parent()) would work as well, .e > * selects all DIRECT children of a class='e' element. The second argument to the $ function works as a scope; it only finds elements under that base element.

It could also be written $(this).parent().find('span span'). The danger of just searching for "span" is it would match the outer span as well - the outer span $('.e', $(this).parent()).text() will return the text of all 3 elements together - which may actually be what you want.

gnarf
thanks for your reply!The issue is this appears multiple times on the page, and I only want it to happen in the div of the link clicked, so it needs to somehow incorporate the $(this) of the mouseclick and move relatively from there...
Mala
Just noticed that caveat upon re-read; added $(this).parent() to the original selector to look only within the parent div, or you could potentially use $(this).prev(); to get the previous sibiling.
gnarf
Thanks! Giving it a try now...
Mala
could you please explain what exactly $('.e > *', $(this).parent()); does? is the '.e > *' part really necessary or could I replace it with 'span' or something similar?
Mala
Ah nevermind, gave it a try and it worked! Thanks!
Mala
a little more explination added at your request - glad it worked for you!
gnarf
+1  A: 
$(this).prev().children(".e").get(0).children()

will get you all children of the previous sibling's first child of class "e".

You could also do this without jQuery, but it's a bit uglier; if you have a reference to the node you're interested in, you're looking for its .previousSibling.getElementsByTagName('span')[0].childNodes -- which is an array.

Meredith L. Patterson