Reputation: 2311
I have 5 div with corresponding id's in a sequence with the following ids (divele1, divele2, divele3, divele4, divele5). Now I have two div ids with with and Now I compare whether one div is previous or net element of another div.
ex: I have divele3 and divele5. Now I want to compare divele5 is previous or next element to divele3.
Any suggestions on the same
Upvotes: 3
Views: 58
Reputation: 337626
Assuming that all the div
elements are children of the same container, like this:
<div class="container">
<div id="divele1">devele1</div>
<div id="divele2">devele2</div>
<div id="divele3">devele3</div>
<div id="divele4">devele4</div>
<div id="divele5">devele5</div>
</div>
Then you can simply use index()
to compare ordinal positions. For example:
var $div5 = $('#divele5');
var $div3 = $('#divele3');
if ($div3.index() < $div5.index()) {
console.log('3 is before 5');
} else {
console.log('5 is before 3');
}
If the #diveleX
divs are not siblings at the same level of the DOM then you would need to give all of them a common class name and then use that in the index()
method, like this:
<div id="divele1" class="divele" />
$('#divele1').index('.divele');
Upvotes: 1
Reputation: 3200
The ~
CSS selector
select a Sibling that come next, so if you can select something like #diveleX ~ #diveleY
means that Y is next to X otherwise come before.
Example:
if ( document.querySelector( '#divele3 ~ #divele5' ) ) {
console.log("divele5 is next to divele3"); // Print this
}
else {
console.log("divele5 is before to divele 3");
}
if ( document.querySelector( '#divele4 ~ #divele3' ) ) {
console.log("divele3 is next to divele4");
}
else {
console.log("divele3 is before to divele4"); // Print this
}
#test > div {
border: 1px solid red;
height: 20px;
margin: 5px;
}
<div id="test">
<div id="divele1">1</div>
<div id="divele2">2</div>
<div id="divele3">3</div>
<div id="divele4">4</div>
<div id="divele5">5</div>
</div>
Upvotes: 0