Get div above the current

Asked

Viewed 115 times

0

I have a set with several Ivs,

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

I am giving each of them, and I need to know what is the number (html) of the div above, for example if I am in div 4 I need to know the number 3 which is the top..

  • Do you want to know the index or HTML that’s in that div?

2 answers

2

You can use the .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>

And yet another example with similar functionality: http://jsfiddle.net/aqfq45hh/

1

That’s right:

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

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

to access his current Journal, use

.index();

In its current context it will be:

$('element').prev().index();

Browser other questions tagged

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