I would like to dynamically style every first and last element in row via css or js.
<div class"box">
<ui>
<li class"one"></li>
<li class"two"></li> First
<li class"two"></li>
<li class"two"></li>
<li class"two"></li> Last
<li class"one"></li> First
<li class"one"></li>
<li class"one"></li>
<li class"one"></li>
<li class"one"></li>
<li class"one"></li>
<li class"one"></li>
<li class"one"></li> Last
<li class"two"></li> First
<li class"two"></li>
<li class"two"></li>
<li class"two"></li>
<li class"two"></li>
<li class"two"></li> Last
</ui>
.two:last-child selects only one and last element in ui, instead of multiple in a raw same issue with .two:last-of-type
CodePudding user response:
Here's a way you could try:
var list = document.getElementById("bigList").querySelectorAll(".two");
list.forEach(function (item) {
if (item.nextElementSibling) {
var nextSibling = item.nextElementSibling;
if (nextSibling.classList.contains("one")) {
item.classList.add("bg-green");
}
}
});
/* First */
.one .two, .two .one {
background-color: red;
}
/* Last */
.bg-green, .two:last-child {
background-color: green;
}
<div class="box">
<ul id="bigList">
<li class="one">1</li>
<li class="two">2</li> <!--First-->
<li class="two">2</li>
<li class="two">2</li>
<li class="two">2</li> <!--Last-->
<li class="one">1</li> <!--First-->
<li class="one">1</li>
<li class="one">1</li>
<li class="one">1</li>
<li class="one">1</li>
<li class="one">1</li>
<li class="one">1</li>
<li class="one">1</li> <!--Last-->
<li class="two">2</li> <!--First-->
<li class="two">2</li>
<li class="two">2</li>
<li class="two">2</li>
<li class="two">2</li>
<li class="two">2</li> <!--Last-->
</ul>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Here is the solution with the code.
<!DOCTYPE HTML>
<HTML>
<head>
<title>Try jQuery Online</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"
type="text/javascript"></script>
<script type="text/javascript">
$( document ).ready(function() {
var cls="one";
var len = $('ui li').length;
$("ui li").each(function(index){
if(cls!=$(this).attr("class")){
$(this).attr("style","background-color:red;");
if(index!=1){
$(this).prev().attr("style","background-color:red;");
}
cls=$(this).attr("class");
}
if(index === (len - 1)){
$(this).attr("style","background-color:red;");
}
});
});
</script>
<style>
</style>
</head>
<body>
<UI>
<li class="one">test</li>
<li class="two">First</li>
<li class="two">test</li>
<li class="two">test</li>
<li class="two">Last</li>
<li class="one">First</li>
<li class="one">test</li>
<li class="one">test</li>
<li class="one">test</li>
<li class="one">test</li>
<li class="one">test</li>
<li class="one">test</li>
<li class="one">Last</li>
<li class="two">First</li>
<li class="two">test</li>
<li class="two">test</li>
<li class="two">test</li>
<li class="two">test</li>
<li class="two">Last</li>
</ui>