Reputation: 4319
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.
Upvotes: 0
Views: 58
Reputation: 643
$('.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();
}
Upvotes: 1
Reputation: 2062
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
Upvotes: 0
Reputation: 78630
You were close. The element is a sibling, not a parent.
$(this).siblings('.pID').text();
Upvotes: 1