1

Suppose I have string selector such as:

input.js-pretty-select[type="radio"].selected

How can I get just all class names (js-pretty-select and selected) from this string, possibly using some jQuery core function?

I thought about some regex at first, but then I realized that jQuery might have that already implemented somewhere in it's code, like when resolving selectors with $().

3 Answers 3

1

You can use this function to extract the classes from a string using regular expression:

// This function accepts a string and return array of classes
function getClasses(s) {
    var matches = s.match(/\.[a-zA-Z][\w-]*/g);
    var classes = [];

    for(var i=0; i < matches.length; i++) {
      classes[i] = matches[i].substr(1);  
    }
    return classes;
}

var c = getClasses('input.js-pretty_3select[type="radio"].selected');
Sign up to request clarification or add additional context in comments.

1 Comment

Both, yours and Krishna's answers are enough for my needs, although regular expressions seem to be more solid, and that's why I mark your answer as correct. Thank you all for responses!
1

How about this:

$("input.js-pretty-select[type='radio'].selected").attr('class')

4 Comments

Unfortunatelly, this returns undefined when such element does not exist in DOM tree...
I am sure you can handle existence of an element in Jquery :) if($("input.js-pretty-select[type='radio'].selected").length)
That is right, but I need these class names regardless of element existence.
You are confusing an element with a selector. The question is asking how to retrieve the class names from the selector, not the element that is matched.
1

JSFIDDLE DEMO => http://jsfiddle.net/s1g2mwor/

var str = 'input.js-pretty-select[type="radio"].selected';

var arr = str.split('.'); //["input", "js-pretty-select[type="radio"]", "selected"]

arr.splice(0, 1); //removing the first entry (input)

for (var i = 0; i < arr.length; i++) {
    arr[i] = arr[i].split('[')[0]; // removing [type="radio"]
};
console.log(arr); //["js-pretty-select", "selected"]

Note: This code will only work for the string you've provided. If you want something more complex your code will need to handle all the complex scenarios

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.