0

In a dom which has many of the blocks like the one below, I'd like to get name of pid element (i.d 123) when link is clicked:

<div class="a-post">
    <a class="pid" name="123"></a>
    <div class="row">
        <p>Some text</p>
    </div>
    <br>
    <div class="row">
        <div class="col-xs-12">
            <p>Othe text </p>
        </div>

        <br>
        <div class="row">
            <div class="col-xs-1">
                <img class="link" src="link.svg">
            </div>

        </div>

    </div>
</div>

Here is my jQuery:

$(document).ready(function () {
  $(".link").click(function () {
    let pid = $(this).parent(".a-post").find(".pid").attr('name');
    console.log('pid is:', pid);
 }
});

But I get pid is: undefined

How can I fix this?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Babr
  • 1,971
  • 14
  • 33
  • 47

1 Answers1

3

You have to use .closest() and not .parent(), because .parent() only goes 1 step up. .closest() will continue until it reach the top or finds the element.

$(document).ready(function() {
  $(".link").click(function() {
    let pid = $(this).closest(".a-post").find(".pid").attr('name');
    console.log('pid is:', pid);
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="a-post">
  <a class="pid" name="123"></a>
  <div class="row">
    <p>Some text</p>
  </div>
  <br>
  <div class="row">
    <div class="col-xs-12">
      <p>Othe text </p>
    </div>

    <br>
    <div class="row">
      <div class="col-xs-1">
        <img class="link" src="link.svg">
      </div>

    </div>

  </div>
</div>
Carsten Løvbo Andersen
  • 26,637
  • 10
  • 47
  • 77