Brett Perla Brett Perla - 1 year ago 42
Javascript Question

How do I retrieve individual text values when all divs have same class

I have a block of research site addresses with hyperlinks allowing users to email the research sites directly. Ultimately, I want some sort of jQuery function that returns the street address above whatever email link the user clicked.

Here is the function I'm working with, with the HTML shown below. Every time I click on 'Email this Site' it returns all of the addresses shown on the page. I would like it just to show the address of the site I'm choosing to email however.



$('.doctor-email').click(function(e){
var address = $('.doctor-address').text();
console.log(address);
})

<div class="doctor-address">740 South Lindy Street<br>J401<br>Burbank,&nbsp;CA&nbsp;40536</div>
<div class="doctor-directions">
<a href="javascript: void(0);" onclick="javascript: ViewMap('https://maps.google.com/?daddr=740+South+Limestone+Street%2c+Lexington%2c+KY+40536');">
Get Directions
</a>
</div>
</div>
<div class="col-sm-6">
<p class="doctor-email">
<a href="javascript: ContactSite('5859')">
Email this site
</a>
</p>
</div>
</div>
</div>
<div class="col-xs-10 col-sm-9">
<div class="row">
<div class="col-sm-6">
<div class="doctor-address">800 South West Street<br>J401<br>Lexington,&nbsp;KY&nbsp;40536</div>
<div class="doctor-directions">
<a href="javascript: void(0);" onclick="javascript: ViewMap('https://maps.google.com/?daddr=800+South+West+Street%2c+Chicago%2c+IL+40536');">
Get Directions
</a>
</div>
</div>
<div class="col-sm-6">
<p class="doctor-email">
<a href="javascript: ContactSite('5859')">
Email this site
</a>
</p>
</div>
</div>
</div>
</div>
<div class="col-xs-10 col-sm-9">
<div class="row">
<div class="col-sm-6">
<div class="doctor-address">900 Delavan Street<br>J401<br>Buffalo,&nbsp;NY&nbsp;40536</div>
<div class="doctor-directions">
<a href="javascript: void(0);" onclick="javascript: ViewMap('https://maps.google.com/?daddr=900+Delavan+Street%2c+Chicago%2c+IL+40536');">
Get Directions
</a>
</div>
</div>
<div class="col-sm-6">
<p class="doctor-email">
<a href="javascript: ContactSite('5859')">
Email this site
</a>
</p>
</div>
</div>
</div>
</div>

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>





I am very new to javascript, so any and all feedback is welcome.

Thanks!
Brett

Answer Source

Try this.

$('.doctor-email').click(function(e){
    //go up to the contextual row, and then find the nested address
    var address = $(this).closest('.row').find('.doctor-address').text();
    console.log(address);
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download