Get div above current

0

I have one set with several divs,

<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>

I'm giving each of them, and I need to know the number (html) of the above div, for example if I'm in div 4 I need to know the number 3 and above.     

asked by anonymous 23.01.2015 / 00:29

2 answers

2

You can use .prev() .

If you want the index:

.prev().index(); // começa em 0, talvez queiras ".prev().index() + 1;"

If you want HTML:

.prev().html();

Example:

var div3 = $('div:eq(2)');
var div2 = div3.prev();

div3.html('eu sou a div 3 com index 2');
div2.html('eu sou a div anterior à 3 com index:' + div2.index());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><div>1</div><div>2</div><div>3</div><div>4</div>

Andyetanotherexamplewithsimilarfunctionality: link

    
23.01.2015 / 00:54
1

That's it:

.prev(); para ir para o elemento irmão anterior.

.next(); para ir para o elemento irmão seguinte.

To access its current index, use

.index();

In its current context it will be:

$('element').prev().index();
    
23.01.2015 / 02:21