'Select visually first element while reordered by flex
Lets say I have a list with display: flex and inner elements reordered with order: NNN;.
So that first element in DOM can be N-th visually.
Is it possible using Javascript ( or some kind of CSS selector )select the element that visually comes first?
<ul style="display: flex; flex-direction: column;">
<li style="order: 2;">1</li>
<li style="order: 12;">2</li>
<li style="order: 0;">select me please</li>
<li>4</li>
</ul>
Solution 1:[1]
Here is a way to give you the order of your elements, you can then use filters on your list to exclude invisible elements or anything you like.
jQuery btw has some helpful functions for such applications, would be a little cleaner with that.
var nList = document.querySelectorAll('li');
var aList = Array.from(nList);
aList.sort(function(a,b) {
var sAOrder = a.style.order ? parseInt(a.style.order) : 0;
var sBOrder = b.style.order ? parseInt(b.style.order) : 0;
return sAOrder-sBOrder;
});
console.log(aList);
<ul style="display: flex; flex-direction: column;">
<li style="order: 2;">1</li>
<li style="order: 12;">2</li>
<li style="order: 0;">select me please</li>
<li>4</li>
</ul>
Solution 2:[2]
I think this should do the trick.
- Calculate with js which is the
<li>with the minimum order value. - Added a class named
.first-elementto that element.
let list = document
.getElementById("list")
.querySelectorAll('li');
const orders = [];
list.forEach((item, index) => {
orders.push(item.style.order);
});
let minVal = Math.min(...orders);
list.forEach((item, index) => {
if (minVal == item.style.order
&& item.style.order !== "" ) {
item.classList.add("first-element");
}
});
.first-element {
background-color: pink;
}
<ul id="list" style="display: flex; flex-direction: column;">
<li style="order: 2;">1</li>
<li style="order: 12;">2</li>
<li style="order: 0;">select me please</li>
<li>4</li>
</ul>
Solution 3:[3]
I needed to do something similar. In my case I was reordering Bootstrap tabs visually. This code works for me:
function showFirstTab() {
var sortedTabs = $('#overviewTab li').sort(function (a, b) {
aOrder = $(a).css('order');
bOrder = $(b).css('order');
var finalA = aOrder ? parseInt(aOrder) : 0;
var finalB = bOrder ? parseInt(bOrder) : 0;
return finalA - finalB;
});
sortedTabs.first().find('button').tab('show');
}
This code is using Bootstrap and jQuery. For some reason, the order values are always blank when I try to get them using plain JavaScript. Somehow, the jQuery version works.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user3154108 |
| Solution 2 | Alberto Rhuertas |
| Solution 3 | Andrew |
