Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How can I change an element's class in JavaScript Language?

How can I change the class of an HTML element in response to an onclick or any other events using JavaScript ?
by

2 Answers

Bharatgxwzm
In one of my old project that didn't utilize jQuery, I assembled the accompanying capacities for adding, eliminating and checking if the component has class:
function hasClass(ele, cls) {
return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}
function addClass(ele, cls) {
if (!hasClass(ele, cls)) ele.className += " " + cls;
}
function removeClass(ele, cls) {
if (hasClass(ele, cls)) {
var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
ele.className = ele.className.replace(reg, ' ');
}
}

Along these lines, for instance, on the off chance that I need onclick to add some class to the catch I can utilize this:
<script type="text/javascript">
function changeClass(btn, cls) {
if(!hasClass(btn, cls)) {
addClass(btn, cls);
}
}
</script>
...
<button onclick="changeClass(this, "someClass")">My Button</button>
Kajalsi45d
Using JavaScript code:
function hasClass(ele, cls) {
return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}

function addClass(ele, cls) {
if (!this.hasClass(ele, cls)) ele.className += " " + cls;
}

function removeClass(ele, cls) {
if (hasClass(ele, cls)) {
var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
ele.className = ele.className.replace(reg, ' ');
}
}

function replaceClass(ele, oldClass, newClass){
if(hasClass(ele, oldClass)){
removeClass(ele, oldClass);
addClass(ele, newClass);
}
return;
}

function toggleClass(ele, cls1, cls2){
if(hasClass(ele, cls1)){
replaceClass(ele, cls1, cls2);
}else if(hasClass(ele, cls2)){
replaceClass(ele, cls2, cls1);
}else{
addClass(ele, cls1);
}
}

Login / Signup to Answer the Question.