I am a newbie with jQuery and trying to extract class name from element with the specific prefix.
I have achieved this by using javascript as below,
Code:
var classes = $('#elementID').attr('class').split(' ');
for (var i = 0; i < classes.length; i++) {
var matches = /^id\-(.+)/.exec(classes[i]);
if (matches != null) {
var resID = matches[1];
}
}
console.log(resID);
<div id="elementID" class="id-3212 sort filter"></div>
By using the above script i can extract the class name which is start with the prefix 'id-' and get the result as 3212. Here i'm trying to extract the whole class name i.e id-3212 using jquery.
I think this can be done in simple and less code using jQuery. How can i extract the whole class name using jQuery ?
Any advice and suggestions will be greatly appreciated!!!!
/^(id\-.+)/would include the id in your regex match<div id="elementID" data-foo="3212" class="sort filter"></div>is much easier to access and read, and avoids having to hack around any identifying strings placed inclassattributes.matches[0]to get the whole match. There's no need for a capture group if you don't want to extract the number.