Utilize jQuery to automatically assign numbers to <h1-h6> headings

Looking to develop a JavaScript function that can automatically number headings (h1- h6) for multiple projects without relying on CSS. Currently achieving this with CSS:

body { counter-reset: h1; }
h1 { counter-reset: h2; }
h2 { counter-reset: h3; }
...

This format is achieved:

1. Heading number 1
1.1. Heading level 2
1.1.1. Heading level 3
...

Desiring to convert this into a JavaScript function and eliminate the need for CSS as below:

if( typeof mbopts !== 'undefined' && mbopts.length > 0 ) {
    var mbopts = {
        levels:    Int,
        separator: String,
        startAt:   Int
    };
}
$('#main').mbheaders(mbopts);

The JavaScript function would operate as follows:

(function(h) {
    h.fn.mbheaders = function( mbopts ) {
        let mbdefaults = {
            levels: 6,
            separator: "decimal",
            startAt: 1
        };

        // Extend the defaults
        let mboptions = h.extend( {}, mbdefaults, mbopts );

        return this.each( function() {
            // Function logic here to handle automatic numbering of headings
            // based on specified options.
        });
    }
}( jQuery ));

This functionality is important for maintaining consistent numbering in documentation split across multiple files such as .md.


Example processed HTML from a markdown file:

<article class="markdown-section" id="main">
    <h1 id="about-this-document">About this document</h1>

    <h1 id="everyone">Everyone</h1>

        <h2 id="logging-into-your-computer">Logging into your computer</h2>

        <ol>
            <li>Step one</li>
            <li>Step two</li>
        </ol>

    <h1 id="special-areas">Special areas</h1>

        <h3 id="on-the-road">On the road</h3>
        <h3 id="remote">Remote</h3>

</article>

Relevant output numbers obtained using the automatic heading numbering:

1. Everyone
1.1. Logging into your computer

2. Special areas
2.1. On the road
2.2. Remote

Answer №1

This initial code snippet provides a starting point for organizing content with different heading variations into sections. It utilizes the jQuery method nextUntil() to group h1 elements within a section and assigns sequential numbers to them based on their order. This script also handles h2 and h3 elements to create a hierarchical structure.

The CSS styling included defines borders for sections and color codes for various headings. The sample HTML demonstrates how this script can be implemented in a document with different sections and headings.

Answer №2

I have just developed a new .ol() method specifically for jQuery. This method is designed to create an ordered list and provide a new instance of a constructor with an additional .li() method. By using the .li() method, you can easily reference the created ordered list. Feel free to start listing away!

function Ol(j){
  const ol = $('<ol></ol>');
  j.append(ol);
  this.li = (title, noIncrement = false)=>{
    let n = noIncrement ? '' : ' '+(ol.children().length+1);
    let li = $('<li>'+title+n+'</li>');
    ol.append(li);
    return li;
  }
}
$(function(){
$.fn.extend({
  ol:function(){
    return new Ol(this);
  }
});
const test = $('#test'), titles = test.ol(), title1 = titles.li('Title'), sections = title1.ol();
for(let i=0,l=10; i<l; i++){
  for(let n=0,chapters=sections.li('Chapter').ol(),q=4; n<q; n++){
    for(let z=0,subs=chapters.li('Section').ol(),c=3; z<c; z++){
      subs.li('sub-section').ol().li('content would go here', true);
    }
  }
}
const title2 = titles.li('Title').ol(), chapter1 = title2.li('Chapter').ol();
const chapter2 = title2.li('Chapter').ol(), chap1Sec1 = chapter1.li('Section').ol();
const chap2Sec1 = chapter2.li('Section').ol();
chap2Sec1.li('sub-section'); chap2Sec1.li('sub-section');
chap1Sec1.li('sub-section').ol().li('This is how you might use outside a loop', true);
});
*{
  margin:0; padding:0;
}
ol{
  list-style:none;
}
ol li{
  margin-left:10px;
}
#test>ol>li{
  margin-left:0;
}
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<div id='test'></div>

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

Building a solid foundation for your project with Node.js and RESTful

I need to integrate a legacy system that offers an api with rest/json queries in Delphi. I plan to consume this data and build an app using angular + nodejs. My goal is for my application (client) to only communicate with my web-server on nodejs, which wil ...

Commencement of timeline utilizing amchart's gantt feature

I am currently utilizing the Gantt chart feature in Amchart. The chart segments are organized based on dates. I am looking to specify a specific initial location for the chart's navigator between two dates, rather than having it applied across the en ...

What is the optimal level of safety logic to incorporate into my proprietary components?

Having developed numerous React components, setting propTypes, writing tests, and occasionally defining default props, I find myself pondering the balance between safety and efficiency. Experimenting with Flow types has led me to consider implementing addi ...

Getting started with jquery plugins: installation and usage

I have some questions as a beginner. Firstly, I'm interested in obtaining this plugin: Unfortunately, I am having difficulty downloading it and seem to be stuck in a loop. Can someone guide me on the exact steps to download it? Secondly, how do I go ...

Implementing changes in the last loop iteration to impact the final result in Vue

Having recently delved into Vue, I'm having trouble figuring out how to solve this issue. Let me begin by showing you the code snippet followed by explaining the problem at hand. Currently, I am utilizing Vue-Good-Table for this project. methods:{ ...

Modifying a div element upon the successful completion of an ajax/json request

Currently, I have a form on my webpage for creating a new album. Alongside this form, there is also a delete album form. After successfully creating an album, I want to automatically update the checkbox list in the delete album form with the details of the ...

Creating a layout with Bootstrap 4 cards split into two rows

I need to change my layout from 3 columns to 2 columns. I know I can achieve this using CSS like the code snippet below, but I'm curious if there's a built-in Bootstrap method for this: .card-columns { -webkit-column-count: 2; -moz-column-co ...

The sidebar on the right side of the screen is content to relax beneath my

The positioning of my sidebar is currently below the content on the left side of the page, but I want it to sit beside the content on the right side. I've tried various solutions from similar questions without success. Here is an example of how I woul ...

The issue regarding the fixed table layout bug in Firefox

Upon testing Firefox 5, it has come to my notice that an additional pixel of space is being added between the right column and the table border due to this particular piece of code: <style type="text/css"> table { border: 1px s ...

Is it time to shake up the location of your Toastr

Recently, I've been working on implementing Toastr from this GitHub repository. While I am able to receive alerts and toasts as intended, I'm running into issues when trying to apply custom options. It seems to only stick to the default settings ...

When you add the /deep/ selector in an Angular 4 component's CSS, it applies the same style to other components. Looking for a fix?

Note: I am using css with Angular 4, not scss. To clarify further, In my number.component.css file, I have: /deep/ .mat-drawer-content{ height:100vh; } Other component.css files do not have the .mat-drawer-content class, but it is common to all views ...

What could be causing the asynchronous function to return a pending promise even after using the await keyword?

I seem to be overlooking something as I cannot comprehend why my promise does not resolve. I have simplified the code to this basic example: ... console.log("before"); const promise = second(); console.log("after"); console.l ...

Insert a 5-second delay in the JavaScript code before triggering the click event on the next button

Currently, I have a JavaScript code in place that is fairly straightforward. The webpage contains about 100 buttons with the class button, and I am successfully simulating clicking each one of them systematically. However, I would like to introduce a dela ...

Make sure that the element with a relatively positioned stays contained within the top container

While relative and absolute positioning can be useful, they have the drawback of taking elements out of the flow which can lead to restrictions in their usage. Recently, I came across one such restriction and I'm interested to see if there is a soluti ...

When a page loads, automatically refreshing a row in MySQL

I've been searching around, but haven't found a solution to my basic issue. I need help with creating a system where a user can only view a page once per day. Currently, clicking a button updates the MySQL Row, but users can bypass this restricti ...

What causes my paragraph textContent to vanish after briefly displaying its value?

As a beginner in JavaScript and HTML, I am taking on the challenge of learning these languages from scratch independently. I have encountered an issue with my code where the word "Hi!" briefly flashes below the "Click Me!" button before disappearing compl ...

The functionality of a basic each/while loop in jQuery using CoffeeScript is not producing the desired results

I've been experimenting with different methods to tackle this issue. Essentially, I need to update the content of multiple dropdowns in the same way. I wanted to use an each or a while loop to keep the code DRY, but my experience in coffeeScript is li ...

Encountered a SyntaxError on JSON Web Tokens Node JS Server: Unexpected token } found in JSON at position 24

Me, along with others, have encountered this issue: SyntaxError: Unexpected token } in JSON at position 24 at JSON.parse (<anonymous>) while following a tutorial on JSON Web Tokens (TUTORIAL LINK: https://www.youtube.com/watch?v=mbsmsi7l3r4&t=34s ...

Attempting to generate a fresh document by duplicating the data from a specific variable

Currently attempting to generate a new csv file within a specific directory. The goal is to save the data of a variable inside the created csv file: handleRequest(req, res) { var svcReq = req.body.svcReq; var csvRecData = JSON.stringify(req.bod ...

Is there a way to trigger a function upon the loading of a template in Angular 2?

I'm a newcomer to angular2 and I need to trigger a function when a template loads or initializes. I have experience with achieving this in angular1.x, but I'm struggling to figure out how to do it in angular-2. Here's how I approached it in ...