0

I have few classnames like this:

<div class=".error .error-code-123">

Now I want to to check whether the .error class has any .error-code-SOME_NUMBER.

I tried something like this:

$(".error").hasClass(/.error-code-[0-9]/)

Just trying to use regex here, which does not work. How can I check the above scenario using jquery?

3
  • Is it possible for you to amend the HTML? This can be made much easier by storing the error code in a data attribute instead of a class. That way you know exactly how to retrieve the value, and can select the elements by it, instead of having to loop over them all and hack the class string around with a regex. Commented Jul 26, 2018 at 9:39
  • No @RoryMcCrossan, it is getting appended by third party api if there is some error. Commented Jul 26, 2018 at 9:41
  • 2
    Yuck. @Zenoo has about the neatest solution for this then. Commented Jul 26, 2018 at 9:42

1 Answer 1

3

You can use the classList property of your element and test if at least one of its classes starts with error-code- using Array#some and String#startsWith :

let result = Array.from($(".error")[0].classList).some(c => c.startsWith('error-code-'));
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="error error-code-123"></div>

Sign up to request clarification or add additional context in comments.

1 Comment

This should be my clear option in the end, thanks for your answer.

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.