1

I need to target the second child of the parent foo. How can I do that?

$("#one").click(function() {
  // How to get "me" if I do not know the classname?
  // I need to target that second div (I know that it's second).
  var q = $(this).eq(1).attr('class');
  console.log(q); // undefined

  // Aim?
  // I need that element or classname
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="one" class="foo">
  <div>one</div>
  <div class="me"></div>
</div>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Sylar
  • 11,422
  • 25
  • 93
  • 166
  • Possible duplicate of [How to get the children of the $(this) selector?](https://stackoverflow.com/questions/306583/how-to-get-the-children-of-the-this-selector) – Maarten Bicknese Sep 26 '17 at 11:33

2 Answers2

3

You need to get the children first and then apply the eq() method.

var q = $(this).children().eq(1).attr('class');

$("#one").click(function() {

  var q = $(this).children().eq(1).attr('class');
  console.log(q); 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="one" class="foo">
1
 <div></div>
 <div class="me"></div>
</div>

Or use the :nth-child selector as the argument of children() method.

var q = $(this).children(':nth-child(2)').attr('class');

$("#one").click(function() {

  var q = $(this).children(':nth-child(2)').attr('class');
  console.log(q); 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="one" class="foo">
1
 <div></div>
 <div class="me"></div>
</div>
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
1

You need to find the second div

$(this).find('div:eq(1)').attr('class')
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339