Apsed1976 Apsed1976 - 1 month ago 7
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
my-class-level
suffix (in this case -
3
)? Order of class attributes can be absolutely random.

Answer

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.