How to select siblings?

3

I'm trying to modify a configuration of a sister div, but I'm having difficulty finding the correct selector to use, I know that html works like a tree, and usually when I need to select a higher element uses parent() and when it is a lower one I use find() .

How would you select a peer?

    
asked by anonymous 03.03.2016 / 20:58

2 answers

5

You can use siblings as the name priprio says "brothers."

Example:

$('#foo').click(function() {
  var t = $(this).siblings(); // Vai pegar todos os irmãos.
  var t2 = $(this).siblings('#bar'); // Vai pegar apenas o irmão com id correspondente.
  var t3 = $(this).siblings('.bar'); // Vai pegar todos irmãos com as classes correspondente.
  console.log(t);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script><divid="foo">FOO</div>
<div id="bar" class="bar">BAR</div>
<div id="bar2" class="bar">BAR2</div>

If you just wanted to get the next sibling, you can also use next() .

    
03.03.2016 / 21:02
2

Another way beyond the @Gabriel Rodrigues response would be to use .parent() and .find() to select which one you want.

See the example below:

$(document).ready(function(){
  $('#btn').click(function(){
    var irma = $(this).parent().find('#irma').html();
    console.log(irma);
    $('#resultado').html(irma);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div><divid="irmao">
    eu sou o irmão
  </div>
  <div id="irma">
    eu sou a irmã
  </div>
  <button id="btn">
    Clica aqui
  </button>
  <p id="resultado"></p>
</div>
    
03.03.2016 / 21:06