0

For example: i have <div class="oneClass twoClass colorRed">Content</div> and i want to find the color* class and replace the color part "Red" with the new value "Blue" or "Yellow" for example so it would be "colorBlue" now...

How do i do that with Javascript only ?

Thanks!

Update: This isn't my question: Change an element's class with JavaScript

Community
  • 1
  • 1
Ben
  • 257
  • 1
  • 15
  • 5
    Sharing your research helps everyone. Tell us what you've tried and why it didn't meet your needs. This demonstrates that you've taken the time to try to help yourself, it saves us from reiterating obvious answers, and most of all it helps you get a more specific and relevant answer! Also see [how to ask](http://stackoverflow.com/questions/how-to-ask) – Cerbrus Jun 19 '15 at 11:47
  • First Google result: http://stackoverflow.com/questions/195951/change-an-elements-css-class-with-javascript – Drakes Jun 19 '15 at 11:49
  • [Read this.][1] Or something else you're looking for. [1]: http://stackoverflow.com/questions/16510973/how-can-i-replace-one-class-with-another-on-all-elements-using-just-the-dom#answer-16511067 – Rajeev Sharma Jun 19 '15 at 11:51
  • Why so much unuseful comments. let the right guy that understand the question answer just like Tomek did and that's it. – Ben Jun 19 '15 at 12:35

2 Answers2

0

var node = document.getElementById('someDiv');
node.className = node.className.replace(/color.*/, 'colorBlue');
/* This css snippet will allow to see 
 * element's classes rendered with the html ;)*/
div:after {
  content: attr(class);
  margin-left: 5px;
  font-style: italic;
  color: gray;
}
<div id="someDiv" class="oneClass twoClass colorRed">Content</div>
Tomek Sułkowski
  • 7,081
  • 2
  • 17
  • 15
  • Great! Thanks! exactly what i meant. – Ben Jun 19 '15 at 12:33
  • The problem with that is that it works only if the class i'm changing is the last one, but if it is the first one it will erase all other classnames... Any Ideas? – Ben Jun 22 '15 at 15:45
  • To solve the problem i have changed it to: /color[A-Z][a-z]+/g – Ben Jun 22 '15 at 18:25
0

Select the div tag. Get the element.className of the div tag so you have the classnames as a string. Use a regular expression to replace the colorRed part of the string with colorBlue. use .className again to set the class of the div to your editted string. If you don't have to support IE, you can use element.classList and its methods.

Shilly
  • 8,511
  • 1
  • 18
  • 24