Reputation: 29877
I have a list of divs and a reference to two that are siblings adjacent to each other. The first div, which I'll call div2 is above div3. How can I tell using jQuery that div2 is directly above div3. Example:
<div id="root">
<div id="div1" />
<div id="div2" />
<div id="div3" />
<div id="div4" />
</div>
Upvotes: 0
Views: 20
Reputation: 1074949
If you mean, "how do I tell whether div2
is immediately before div3
," the answer is that you can check previousElementSibling
or jQuery's prev
:
// If `div3` and `div2` are DOM elements
if (div3.previousElementSibling === div2) {
// ...
const div2 = document.getElementById("div2");
const div3 = document.getElementById("div3");
console.log(div3.previousElementSibling === div2);
<div id="root">
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<div id="div4"></div>
</div>
// If `div3` and `div2` are jQuery objects
if (div3.prev()[0] === div2[0]) {
// ...
const div2 = $("#div2");
const div3 = $("#div3");
console.log(div3.prev()[0] === div2[0]);
<div id="root">
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<div id="div4"></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
If you want to see if they're visually one above the other, you'll want to look at their bounding rectangles.
Upvotes: 1