Reputation: 1
I have a CSS counter that counts my list items and adds the number to the ::before content, however when I remove a certain list element, the numbers shift to reflect an accurate list numbering. I don't want the numbers to change after removing one that is using the counter. This is some example code of my problem:
function remove() {
document.getElementsByClassName("list-item")[0].style.display = "none";
}
.number-list {
list-style-type: none;
counter-reset: list-count 0;
}
.list-item {
counter-increment: list-count 1;
}
.list-item::before {
content: counter(list-count) ". ";
}
<div>
<ul class="number-list">
<li class="list-item">Canada</li>
<li class="list-item">The U.S.A.</li>
<li class="list-item">Mexico</li>
</ul>
<button onclick="remove()">Set first list item display to none</button>
</div>
I tried messing around with the counters but to no avail. Any solutions?
Upvotes: -1
Views: 412
Reputation: 23518
If you have a dynamic set of list items, you could consider setting their counter value with JavaScript with counter-set
so that the counter value does not depend on any previous sibling elements.
function remove() {
document.getElementsByClassName("list-item")[0].style.display = "none";
}
document
.querySelectorAll('.number-list > .list-item')
.forEach((item, i) => {
item.style.counterSet = `list-count ${i + 1}`;
});
.number-list {
list-style-type: none;
counter-reset: list-count 0;
}
.list-item {
counter-increment: list-count 1;
}
.list-item::before {
content: counter(list-count) ". ";
}
<div>
<ul class="number-list">
<li class="list-item">Canada</li>
<li class="list-item">The U.S.A.</li>
<li class="list-item">Mexico</li>
</ul>
<button onclick="remove()">Set first list item display to none</button>
</div>
Upvotes: 0