javascript – How to select sibling elements?

Question:

I'm trying to modify a configuration of a sister div, but I'm having trouble finding the correct selector to use, I know the html works like a tree and, usually when I need to select a superior element I use parent() and when it's a bottom I use find() .

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

Answer:

You can use siblings as the 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 get the next sibling, you can also use next() .

Scroll to Top