Apsed1976 Apsed1976 - 1 year ago 63
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download