0

I have been using the replace function since long to remove the classes from JavaScript, Now I was making the JavaScript function for that through which, I can pass an element and the class name to remove the class from the same.

changeAddress.className = changeAddress.className.replace(new RegExp('(?:^|\\s)' + 'hide' + '(?:\\s|$)'), ' ');

Or

document.getElementById("MyID").className =
    document.getElementById("MyID").className.replace(/\bMyClass\b/,''); 

So can someone suggest me how to pass the class "hide" and "MyClass" Dynamically in the same?

Gaurav joshi
  • 1,743
  • 1
  • 14
  • 28
vaibhav
  • 762
  • 2
  • 12
  • 34
  • 1
    The answer to your literal question is here: [Javascript Regex: How to put a variable inside a regular expression?](http://stackoverflow.com/questions/4029109/javascript-regex-how-to-put-a-variable-inside-a-regular-expression). However, there is a much better solution for the actual problem you are trying to solve. – Felix Kling Jan 10 '17 at 07:06

1 Answers1

3

To remove the class from an element, use classList API

document.getElementById('MyID').classList.remove('MyClass');
Tushar
  • 85,780
  • 21
  • 159
  • 179
  • 1
    Seems like a conflict between answering the literal question (or closing as a duplicate in this case) and providing the right solution to the problem :-/ Good answer! Feel free to reopen the question. – Felix Kling Jan 10 '17 at 06:04
  • @FelixKling Thanks. I've reopened question. :) – Tushar Jan 10 '17 at 07:01
  • Yes.. @FelixKling I believe this is a better solution for my problem, that's why I have accepted this as the solution. – vaibhav Jan 10 '17 at 08:43