0

If I have code like this:

<div class="container">
  <span class="pID">12342123</span>
  <a href="#" class="but">click here</a>
</div>

<div class="container">
  <span class="pID">98765432</span>
  <a href="#" class="but">click here</a>
</div>

<div class="container">
  <span class="pID">2342342</span>
  <a href="#" class="but">click here</a>
</div>

How do I make it so if the link is clicked on, go to the pID and grab the # within the a's own container?

$('.but').on('click',function(){
   var pID = $(this).parent('pID').text(); ?
});

For your information, I don't have any control of putting the PID in the anchor.

halfer
  • 19,824
  • 17
  • 99
  • 186
Damien
  • 4,093
  • 9
  • 39
  • 52

3 Answers3

1

You were close. The element is a sibling, not a parent.

$(this).siblings('.pID').text();
James Montagne
  • 77,516
  • 14
  • 110
  • 130
1
$('.but').on('click',function(){
   var pID = $(this).siblings('.pID').html();
});

Some considerations on whether to use .text() or .html():

What is the difference between jQuery: text() and html() ?

If using as a callable function called as onClick="doThis(this);":

function doThis(el) {
    var pID = $(el).siblings('.pID').html();
}
Community
  • 1
  • 1
Code Monkey
  • 643
  • 6
  • 18
0

try this:

$('.but').on('click',function(){
  var pID = this.parentElement.children[0].textContent
});

assumes the html structure does not change (e.g. children[0] is always the span you are looking for

toms
  • 1,760
  • 1
  • 16
  • 17