shanky
shanky

Reputation: 801

Access children value jquery

In below html I am clicking on id=2 then id=2, how can I access span tag Harr kane value in jQuery using sibling?

<div class="parentId">
   <span class="span1">
      <i class="i1">p</i>
      <span>Harr Kane</span>
   </span>
   <a class="a1" href="">
    <i id="2" class="i1">i1</i>
   </a>
</div>

Upvotes: 0

Views: 35

Answers (2)

guradio
guradio

Reputation: 15555

$('#2').click(function() {

  console.log($(this).closest('div.parentId').find('.span1').find('span').text()) 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="parentId">
  <span class="span1">
      <i class="i1">p</i>
      <span>Harr Kane</span>
  </span>
  <a class="a1" href="">
    <i id="2" class="i1">i1</i>
  </a>
</div>

Using .closest() to get the the div. Using .find() to target the correct element

Upvotes: 0

Rino Raj
Rino Raj

Reputation: 6264

$(this).parent().prev().find('span:first').text();

$(this) - To select currently clicked element.

.parent() - Will give the parent of the currently selected element.

.prev() - will select the previous element.

.find() - is used to find an element inside the selection.

:first - is a pseudo selector used to select the first matching selection.

.text() - to extract the text inside the selection

Working Demo

$(document).ready(function(){
    $("#2").click(function(e){
        e.preventDefault()
        alert($(this).parent().prev().find('span:first').text());
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parentId">
   <span class="span1">
      <i class="i1">p</i>
      <span>Harr Kane</span>
   </span>
   <a class="a1" href="">
    <i id="2" class="i1">i1</i>
   </a>
 </div>

Upvotes: 2

Related Questions