0

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!!!!

3
  • 1
    /^(id\-.+)/ would include the id in your regex match Commented Jul 1, 2020 at 14:41
  • 1
    If you have control over the HTML I would suggest you change it. <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 in class attributes. Commented Jul 1, 2020 at 14:49
  • 1
    Use matches[0] to get the whole match. There's no need for a capture group if you don't want to extract the number. Commented Jul 1, 2020 at 14:51

1 Answer 1

1

You can use element.classList to get an array-like list of all the classes.

Convert the classList to a "real" array then you can use .filter with .startsWith (or a regex here if need really old browsers that don't have .startsWith (or a polyfill))

var id = [...document.getElementById("elementID").classList].filter((x) => x.startsWith("id-"))[0];

console.log(id)
<div id="elementID" class="id-3212 sort filter"></div>

To get the classList if you already have a jquery object:

$('#elementID').get(0).classList

As an alternative, you may find it easier to add data via a data- attribute rather than a one-off class name (assuming you'll have classes such as id-1 id-0099)

<div id="elementID" class="sort filter" data-id="3212"></div>
Sign up to request clarification or add additional context in comments.

1 Comment

@Barmar good call, forgot the split(' ') when looking into classList

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.