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

What is the process of creating a model instance in a Nodejs controller?

Trying to work with the model object in Node using the sequelize module. It looks something like this: File structure: models index.js user.js controllers userController.js routes route.js ========================== models/users.js //created us ...

Enhancing Vertical Expansion of List Items (Twitter Ticker) through Responsive Design

Hey there! I've added a Twitter feed to my website, and you can check it out here: anibalcascais.com/tweet/twitter.html I'm working on making the layout of the feed responsive. Right now, the container div adjusts nicely, but when the browser wi ...

How can you selectively export a single function from a JavaScript file?

Within my project, I have two separate modules - one written in ts and the other in js. There is a utility within the js module that needs to be accessed by the ts module. The utility service.js looks like this: module.exports = { helloFriends: functi ...

Retrieve the content of a specific HTML tag using JavaScript

Is it possible to extract the content of a specific HTML tag as a string or XML format? <body> <script src="jquery.min.js"> //var test = document.getElementsByTagName("input"); //alert(test[0]); $(document).ready(function ( ...

What are the steps to connect to multiple databases with ExpressJS?

I have a server with 3 databases containing identical tables. The databases are named DB1, DB2, and DB3. When working with a specific database, I utilize the following code in app.js: var cnxDB = require('./routes/cnxDB'); app.post('/user ...

Whenever the page is refreshed, the vertical menu bar with an accordion feature hides the sub

I have designed a vertical accordion menu bar following the example at http://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_accordion_symbol However, I am encountering an issue where clicking on a button to display a submenu causes the page to refr ...

Changing the appearance of a specific child component in React by referencing its id

There is an interface in my code. export interface DefaultFormList { defaultFormItems?: DefaultFormItems[]; } and export interface DefaultFormItems { id: string; name: string; formXml: string, isDefaultFormEnable: boolean; } I am looking ...

How to Show a Div When Clicking using Javascript

Looking for a way to toggle the visibility of a div element on click and hide it when clicked anywhere else. window.addEventListener('load', function() { $$('a.tooltip').each(function(link) { var tooltip = document. ...

Personalizing the label of a select input using materialui

Working on customizing a select element using the "styled" method: const StyledSelect = styled(Select)` height: 2rem; color: #fff; border-color: #fff; & .${selectClasses.icon} { color: #fff; } & .${outlinedInputClasses.notchedOutl ...

Best approach for retrieving and adding a large number of images when dealing with slower connections

Currently, I am retrieving 100-200 images using a combination of ajax-php-mongodb. The process involves ajax making an initial call with parameters, php on the server side locating the appropriate mongo document containing all image file ids in grid fs, fe ...

Utilize the useState hook to update state when changes occur in the

I currently have a functional component that utilizes a useState hook. The values it holds are sourced from my redux store, and I aim to update the state with the new store state every time an action is dispatched. At the moment, I've manually set an ...

Unfulfilled commitment on bcrypt

I am currently facing an issue while trying to validate a user's password using bcryptjs. I have implemented a function that returns a Promise, but I am encountering an error when reaching the bycrypt.hash step - all I see is Promise { <pending> ...

Tips on keeping Bootstrap Modals out of your browsing history

Imagine this scenario A visitor lands on Page A, clicks through to Page B, and then engages with a link that triggers a modal (code provided below) <a href="mycontent.html" data-target="#modal_xl" data-toggle="modal" data-backdrop="static">Click me ...

Swapping out a class or method throughout an entire TypeScript project

Currently, I am working on a software project built with TypeScript. This project relies on several third-party libraries that are imported through the package.json file. One such library includes a utility class, utilized by other classes within the same ...

Looping through multiple Ajax requestsIn this scenario, we need

Here's the snippet of code I'm working with: for (var i = 0; i < 20; i++) { $.ajax({ type: "GET", async: false, url: "/MyController/MyMethod", success: function (data) { if (i == 0) { $('#result_progre ...

Using the Firefox API to determine if a tab is currently active

I remember hearing about a feature that was introduced in some recent versions of Firefox allowing developers to check if a tab is active or not using JavaScript. However, I am having trouble finding more information about it online. Can you share the li ...

Placing a moveable object in a designated spot for dropping at the desired location

I've been attempting to clone and drop a draggable object at the exact position within a droppable area where the drop event takes place. While I have come across examples online that demonstrate appending draggables to droppables, they all tend to re ...

IE does not render the output of multiple AJAX requests

Desiring an autocomplete feature for an input box that displays results in a div below it, I wrote this shortened code. It functions flawlessly on Chrome and Firefox - when searching for "Eggs" and then "Milk", their respective results appear. However, Int ...

What could be the reason for this simple sails socket not functioning properly?

Just curious why the simple web socket code below isn't functioning? io.socket.on('user', function(event){ console.log("RECEIVED EVENT:",event); }) I have included sails.io.js in my index file and the above code is located in a test.js ...

Transforming Form Sections for Sending via Ajax in ASP.NET MVC

In the process of developing an application for a tractor salvage yard, I have encountered a challenge. The application allows users to create notes and add multiple parts to each note. Previously, when the create view was on a separate page with its own U ...