Apsed1976 Apsed1976 - 7 months ago 37
HTML Question

How to get class's numeric suffix?

There's a class:

<div id="my-id" class"my-class my-class-level-3"></div>

How can I get its numeric
suffix (in this case -
)? Order of class attributes can be absolutely random.


This is how I would do It:

"use strict";

function getSuffix(element) {
    let match;

    if ( match = element.className.match(/my-class.+my-class-level-(\d+)/) )
        return match[1];

    return null;


console.log(getSuffix({className: 'my-class random class names my-class-level-5'}));

Or you can just set a custom attribute like level="9" and retrieve it using .getAttribute. or better using data-level="9" and get it using .dataset.level.

Hope this helps.