Hello, I would like to know if I am interpreting the command wrongly, or if I am doing something wrong in the implementation.
Translating freely, closest
means "closest". But by clicking on an element and asking for closest()
of it, it brings me the element itself.
In the following snippet, I wanted it to be alert
in the counter of the previous line, but if you click on line 3, it returns undefined
$('tr').click(function () {
var linha = $(this)
var cont = linha.attr('contador')
var ant = (cont - 1);
alert(
linha.closest('tr[contador="' + ant + '"]').attr('contador')
)
});
tr{
line-height: 40px
}
.vermelho{ background-color: red; }
.verde{ background-color: green; }
.azul{ background-color: blue; }
.amarelo{ background-color: yellow; }
.roxo{ background-color: purple; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><tablewidth="500px">
<tr id="tr-1" contador="1" class="vermelho"><td>teste 1</td></tr>
<tr id="tr-2" contador="2" class="azul"><td>teste 2</td></tr>
<tr id="tr-3" contador="3" class="verde"><td>teste 3</td></tr>
<tr id="tr-4" contador="4" class="amarelo"><td>teste 4</td></tr>
<tr id="tr-5" contador="5" class="roxo"><td>teste 5</td></tr>
</table>
The documentation on the site of JQuery
reads as follows:
Travels up the DOM tree until it finds a match for the supplied selector
So (correct me if I'm wrong), he should find the top line, right? As it traverses the DOM above it. Or am I misunderstanding? How should .closest()
work then?