yasarui
yasarui

Reputation: 6573

How to select the grandparent of an element in jquery

In my site i am having the following code.i want to get the href of the anchor element which is the grand parent of the iframe.how i can get the href of the anchor element when starting from the iframe

<a href="https://www.google.co.in/?gfe_rd=cr&ei=LrrLVpa7BuKK8Qf7wo_wCg&gws_rd=ssls" >
  <section class="section">
     <iframe width="560" height="318" class="product-card-media" src="https://www.youtube.com/embed/ZLls1Wn6070?rel=0&amp;autohide=0&amp;modestbranding=1&amp;showinfo=0&amp;enablejsapi=1" frameborder="0" enablejsapi="1" allowfullscreen="" id="fitvid1"></iframe>
  </section>
</a>

Upvotes: 3

Views: 2375

Answers (1)

Richard Hamilton
Richard Hamilton

Reputation: 26444

To traverse up the DOM tree, use closest

$("button").on('click', function() {
  $("#href").html($("iframe").closest("a").prop("href"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<a href="https://www.google.co.in/?gfe_rd=cr&ei=LrrLVpa7BuKK8Qf7wo_wCg&gws_rd=ssls" >
  <section class="section">
     <iframe width="560" height="318" class="product-card-media" src="https://www.youtube.com/embed/ZLls1Wn6070?rel=0&amp;autohide=0&amp;modestbranding=1&amp;showinfo=0&amp;enablejsapi=1" frameborder="0" enablejsapi="1" allowfullscreen="" id="fitvid1"></iframe>
  </section>
</a>

<button>Get Href</button>

<p id="href"></p>

Upvotes: 1

Related Questions