'How to target last flex item
I have a list of divs that can be either display:none or display:flex dynamically depending on a few conditions.
How do I check, since this is dynamic, what is the last div showing display flex?
My code is something like this:
<div class="container">
<div style="display: flex"></div>
<div style="display: none"></div>
<div style="display: flex"></div>
<div style="display: none"></div>
</div>
As I say, the children might or might not be display:flex and might not necessarily be in this order or might be more items than this or not. I need to identify the last item with display:flex so I apply a borderBottom with javascript.
Solution 1:[1]
I need to identify the last item with
display:flexso I apply a borderBottom with javascript.
Since you have js available, consider using a CSS selector targeting the display: flex:
div[style="display: flex"]
Then get the last item in the array (eg: using pop()), thats the items you're looking for.
Pure css this won't be possible.
const e = [ ...document.querySelectorAll('div[style="display: flex"]') ].pop();
e.style.border = '1px solid red';
<div class="container">
<div style="display: flex">a</div>
<div style="display: none">b</div>
<div style="display: flex">c</div>
<div style="display: none">d</div>
</div>
Solution 2:[2]
change your styles to a class
<div class="container">
<div class="flex">a</div>
<div class="none">b</div>
<div class="flex">c</div>
</div>
A function to get it by class name
function le(){
const container = document.querySelector(".container")
const elements = container.getElementsByClassName("flex")
return elements.item((elements.length - 1))
}
console.log(le())
and some csss
.flex {
display: flex
}
.none {
display: none
}
Solution 3:[3]
this is a simplest solution
$(".container").each(function() {
$('div:visible:last', this).css("background","red");
});
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div style="display: flex">1</div>
<div style="display: none">2</div>
<div style="display: flex">3</div>
<div style="display: none">4</div>
</div>
</body>
</html>
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 | |
| Solution 2 | net-js |
| Solution 3 | Robin Hood |
