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 >
<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.
CodePudding user response:
I need to identify the last item with
display:flex
so 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 >
<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>
CodePudding user response:
change your styles to a class
<div >
<div >a</div>
<div >b</div>
<div >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
}
CodePudding user response:
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 >
<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>