Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery get the rest of the element's class name that starts with string "whatever-"

I have js that caches classes that's name starts with "whatever-",

$('[class^="whatever-"], [class*=" whatever-"]')

but what I want now to do is get the rest of the name, for example in case of "whatever-9" I want to get "9", I don't know how to do it, can you help me?

like image 781
Irakli Avatar asked Aug 10 '13 06:08

Irakli


People also ask

How do you check if an element has a specific class in jQuery?

jQuery hasClass() Method The hasClass() method checks if any of the selected elements have a specified class name. If ANY of the selected elements has the specified class name, this method will return "true".

How check class name is available or not in jQuery?

The hasClass() is an inbuilt method in jQuery which check whether the elements with the specified class name exists or not. Syntax: $(selector). hasClass(className);

What is $$ in jQuery?

$ is another, which is just an alias to jQuery . $$ is not provided by jQuery. It's provided by other libraries, such as Mootools or Prototype.


2 Answers

Try this

var check = "whatever-";         
    $('[class^="whatever-"], [class*=" whatever-"]').each(function () {    
        // Get array of class names   
        var cls = $(this).attr('class').split(' ');       
        for (var i = 0; i < cls.length; i++) {
            // Iterate over the class and log it if it matches
            if (cls[i].indexOf(check) > -1) {        
                console.log(cls[i].slice(check.length, cls[i].length));
            }       
        }    
    });

This should also work for the case when there is more than 1 class. There may be cleaner ways of doing this by using filter method and a bit of regex

Check Fiddle

A little cleaner using map

var check = "whatever-";
$('[class^="whatever-"], [class*=" whatever-"]').each(function () {
    var className = this.className;

    var cls = $.map(this.className.split(' '), function (val, i) {
        if (val.indexOf(check) > -1) {
            return val.slice(check.length, val.length)
        }
    });

    console.log(cls.join(' '));
});

Map demo

like image 161
Sushanth -- Avatar answered Oct 22 '22 21:10

Sushanth --


Maybe there are better ways, but this works. Check the console.

DEMO

$('[class^="whatever-"], [class*=" whatever-"]').each(function () {
    var classname = this.className;
    var classsparts = classname.split('whatever-');
    var result = classsparts[1]
    console.log(result);
});

This is assuming you just have one class in the elements you are targeting with your selectors.

like image 37
Sergio Avatar answered Oct 22 '22 20:10

Sergio