Change the order of numbering in ordered lists

I am seeking a way to change the ordering of an ordered list to be in descending order. You can view a live example here.

Instead of having the counter span multiple ol elements, I would like the counter to reset after each ol.

For the live demo, the desired result should look like this:

[3] 1
[2] 2
[1] 3

[2] 4
[1] 5

Does anyone know how to modify the code from the live demo or have a better solution that is widely supported by browsers to achieve this behavior?

Furthermore, is there a method to make the square brackets "copyable" for pasting into Word documents or any open-source alternative? Currently, copying only extracts the numbers without the brackets.

Answer №1

In order to properly format the numbered list, you must assign a specific value to the counter-reset property for each ol, making sure it is equal to one more than the number of child elements within that list.

var ol_elements = document.getElementsByTagName("ol");
//console.log(ol_elements[0].children.length)
for (var i = 0; i < ol_elements.length; i++) {
  ol_elements[i].setAttribute('style', 'counter-reset: item ' + (ol_elements[i].children.length + 1));
}
body {
  font: 13px Verdana
}

ol {
  list-style-type: none;
  margin-left: 20px;
  padding: 0px;
}

ol>li {
  counter-increment: item -1;
}

ol>li:before {
  content: "[" counter(item) "]";
  padding-right: 10px;
}
<div id="content">
  <ol>
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ol>
  <ol>
    <li>4</li>
    <li>5</li>
  </ol>
  <ol>
    <li>6</li>
    <li>7</li>
    <li>8</li>
    <li>9</li>
  </ol>
</div>

Answer №2

To achieve this, utilize CSS counters. By applying a :before pseudo-element to the li element, you can display the count.

Set the counter reset on the ol element so that the count resets with each new instance of an ordered list. This eliminates the need to manually track the number of lists or the items within each list. Additionally, you can configure the counter to include nested lists within the li items, displaying them as 1.1, 1.2, and so forth.

You have the flexibility to restart the count for each individual order list and customize counts and displays for different lists. This gives you full control over the structure.More on using CSS counters here

UPDATE: Following @Bhuwan Bhatt's suggestion, a JavaScript-only approach has been added for setting the counter via querySelectorAll. It first selects all ols in the document and then retrieves the number of lis within each ol. The counter is then set to the length of lis (+1 due to zero indexing).

var lists = document.querySelectorAll('ol');
var listsLength = lists.length;

for (i=0; i<listsLength; i++) {
 var lis = lists[i].querySelectorAll('li');
 var lisLength = lis.length + 1;
 lists[i].style.counterReset = 'section ' + lisLength;
}
ol {
  list-style: none;
  padding-left: 0;
  counter-reset: section ; /* Creates a new instance of the
                                section counter with each ul
                                 element - count set to 4 
                                 because of zero indexing of the list */
}

li::before {
  counter-increment: section -1;   /* Using a negative number 
                                    to decrement the count */
  
  content: counter(section);  /* Display the count as :before element */
  margin-right: 15px;  /* provide a margin between the count and the li */
}
<ol>
  <li>test 1</li>
  <li>test 2</li>
  <li>test 3</li>
 </ol>
 
 <ol>
  <li>test 1</li>
  <li>test 2</li>
  <li>test 3</li>
  <li>test 3</li>
 </ol>
 
 <ol>
  <li>test 1</li>
  <li>test 2</li>
 </ol>

Answer №3

Utilizing flex and setting the column-reverse value in a column direction allows for reversing the list order along with the numbers. To maintain the original data order, a simple jQuery script can be used:

$('ol.reverse').each(function() {
  $(this).append($(this).children('li').get().reverse());
})
ol.reverse {
  display: flex;
  flex-direction: column-reverse;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol class="reverse">
  <li>aa</li>
  <li>ab</li>
  <li>ac</li>
</ol>

<ol class="reverse">
  <li>a</li>
  <li>bb</li>
  <li>cccc</li>
  <li>ddddd</li>
</ol>


<ol>
  <li>a</li>
  <li>bb</li>
  <li>cccc</li>
  <li>ddddd</li>
</ol>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

My React/Redux App is experiencing difficulties as the state fails to load

Currently, I am working on a project based on the Redux Documentation page. Instead of uploading it directly to Stack Overflow, I decided to share my progress on GitHub: https://github.com/davidreke/reduxDocumentationProject I have completed the instructi ...

Utilize fixed values in type declaration

Strange Behavior of Typescript: export type MyType = 0 | 1 | 2; The above code snippet functions correctly. However, the following code snippet encounters an issue: export const ONE = 1; export const TWO = 2; export const THREE = 3; export type MyType = O ...

Incorporate some flair into the Twitter iframe with a Style tag

I have been attempting to add a style tag into the head of an embedded Twitter timeline in order to customize some of the styling. I wrote the CSS and added it within a style tag. My initial idea was to inject this into the iframe using jQuery, but unfortu ...

add text nodes with unnecessary quotation marks around my selection list

Looking to incorporate a select list into my website using a button. I must utilize nodes for access within the DOM to retrieve its value later, so innerHTML isn't an option. Experiencing difficulty as createTextNode seems to encase my list in quota ...

Is it possible to use only CSS to determine if text has wrapped and apply different styles to it?

Let's say we have a button with lengthy text: [Click here to find out more] Due to its length, the text may be split on smaller screens like this: [Click here to find out more] The goal is to align the text to the left when wrapped and to the ce ...

What strategies can I employ with flexbox to achieve my design goals?

How can I achieve my design requirements using flexbox? design requirements The current code that I have implemented follows the flexbox approach to meet the design requirements. However, the output of this code does not match the screenshot of my design ...

Trigger ExtJS input file event when dialogue window is closed

How can we capture the event when a file is selected in an open dialogue box and the OK button is clicked in extjs? **Off topic, the field does not stretch from its normal width. xtype: 'textfield', fieldLabel: 'New (JPG or ...

Challenges arise when using Bootstrap 4 for country selection

There have been reports that bootstrap 4 country select is not functioning properly. In an effort to troubleshoot, I delved into the documentation to find a solution. To make bootstrap-select compatible with bootstrap 4, refer to: Bootstrap 4 beta-2 ...

Validating whether a condition aligns with any element within an array in JavaScript

Is there a better approach to determine if a condition matches any value in an array? For example, if I want to implement retry logic when receiving a 5xx error. var searchUserRequest = httpClient.request(searchUserRequestOptions, (res => { if(r ...

I'm unsure of the process for obtaining record IDs when deleting records with jQuery

<script type="text/javascript" src="../js/jquery-1.4.1.min.js"></script> <script type="text/javascript"> $("#submit").click(function (){ var name =$("#name").val(); var mobile =$("#mobile").val(); var email =$("#email").val( ...

Using jQuery's sortable functionality to rearrange rows in a table can cause conflicts with Angular's orderBy feature

In the past, my angular app used a table with orderBy to sort rows based on a specific column. By clicking on a table header, the orderBy arguments would change and the list would be sorted according to the values in that column. Now, I am experimenting w ...

Guidelines for validating email input using jQuery

Although I am not utilizing the form tag, you can still achieve form functionality using jQuery Ajax. <input type="email" placeholder="Email" name="email" /> <input type="password" placeholder="Password ...

Is there a way to remove or replace the existing polyline to ensure that only one is displayed at a time?

My goal is to have a single line drawn from the closest marker to a static position. I can determine which marker is the closest by sorting the distances, but if a new marker is added and is closer than the previous closest one, a new polyline is drawn wit ...

Using .change(); in JavaScript code with jQuery does not trigger a function

Here we have a generic code example for a jQuery function: $(document).ready(function() { if (something) { // This does something } else if (something else) { // This does something else } else { // And this does somethin ...

How to eliminate a particular validator from a form group in Angular

My goal is to eliminate the specific validator from the validator array so that I can reconfigure the controls when certain values have changed. I am aware of the traditional solution where I would need to repeatedly set validators. checked(event: MatC ...

Filtering nested arrays in Angular by cross-referencing with a navigation menu

In the legacy application I'm working on, we have a navigation menu along with a list of user roles. Due to its legacy nature, we have accumulated a significant number of user roles over time. The main goal is to dynamically display the navigation me ...

Encountering an EJS error stating SyntaxError: a closing parenthesis is missing after the argument list in the file path C:Userscomputer pointDesktopproject2viewshome.ejs

Struggling to retrieve data from app.js through ejs and encountering an error. Pursuing a degree in Computer Science <%- include('header'); -%> <h1><%= foo%></h1> <p class = "home-content">It is a fact that readers ...

A guide on utilizing nodejs to automatically open the default browser and direct it to a specific web address

I am currently developing a program using Node.js. One of the features I aim to implement is the ability to launch the default web browser and direct it to a particular URL. I want this functionality to be compatible across Windows, Mac, and Linux operat ...

Execute CSS within jQuery code only when the body class is present

I am attempting to use CSS (display: none;) within a script to hide elements from my menu only if a specific language is active. When the body class changes from one language to another, I want the script to check if the body class of a certain language ...

Trouble with HTTPS request in Android fragment

My app crashes and returns to the main activity whenever I try to use the search function with the Kitsu API in my fragment. I have observed through Logcat that no data is being fetched, but I am unable to determine what is causing the crash.The LogCat r ...