How to select the sibling elements?

Asked

Viewed 10,585 times

3

I’m trying to modify a configuration of a sister div, but I’m having a hard time finding the correct selector to use, I know that html works as a tree and, usually when I need to select a higher element using the parent() and when it comes to an inferior I use the find().

How would it be to select one of the same level?

  • 2

    Post the structure that is to be easier to help you. Take advantage and make a [tour] and better understand how the site works.

2 answers

6


You can use siblings as the first name 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>
<div id="foo">FOO</div>
<div id="bar" class="bar">BAR</div>
<div id="bar2" class="bar">BAR2</div>

if you just wanted to catch the next brother, you can also use the next().

2

Another way beyond the answer of @Gabriel Rodrigues would use the .parent() and the .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>
  <div id="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>

  • This scenario only works if you have Ids for your elements. In a more common scenario, where one searches for tags and/or classes, this way you would take the sibling elements + the element itself.

  • @Frenetic I agree with you. But I I asked for more explanations on the specific problem, and as I did not get I decided to just post this other way.

  • Recalling also that the .parent() and the .find() not only work with element Ids, I’m using this way for demonstration.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.