Reputation: 1788
I have a part of code in which the function removeClass
must delete an element of array in case, if some of his elements coincides with input parameters.
But it does not work.
var obj = {
className: 'open menu'
};
function removeClass(obj, cls) {
var arr = obj.className.split(' ');
for (var i = 0; i < arr.Length; i++) {
if (cls == arr[i]) delete arr[i]
}
obj.className = arr.join(' ');
return obj.className;
}
console.log(removeClass(obj, 'open'));
// desired output obj.className='menu'
// actual output 'open menu'
Upvotes: 1
Views: 73
Reputation: 10965
Try this:
var obj = {
className: 'open menu dogs cats'
};
function removeClass(obj, cls) {
return (obj.className = obj.className.split(' ').filter(item => cls !== item).join(' '));
}
console.log(removeClass(obj, 'open'));
console.log(removeClass(obj, 'dogs'));
But if you are trying to do this to a DOM element then use classList
instead.
var el = document.getElementById("mine");
console.log(el.className);
el.classList.remove('open');
console.log(el.className);
el.classList.remove('dogs');
console.log(el.className);
<div id="mine" class="menu open dogs cats"></div>
Upvotes: 1
Reputation: 6546
You can use Array.prototype.filter()
method for this.
var obj = {
className: 'open menu'
};
function removeClass(obj, cls) {
var arr = obj.className.split(' ');
obj.className = arr.filter(function(item) {
return cls !== item;
}).join(' ')
return obj.className;
}
console.log(removeClass(obj, 'open'));
In your code, you have used arr.Length
. Actual syntax is arr.length
. But even if you use fix your code then, it will not delete the item instead put undefined
on its place, then you have to handle extra white spaces. That's why I think above solution is good.
Upvotes: 3
Reputation: 526
With ES6 you can even make this really short
function removeClass(element, classToRemove) {
return element.className.split(' ')
.filter(class => class !== classToRemove)
.join(' ');
}
If you want to modify the element itself, just reassign the return value to element.className
Upvotes: 0
Reputation: 1865
Why just don't replace the string?
var obj = {
className: 'open menu'
};
function removeClass(obj, cls) {
return obj.className = obj.className.replace(cls, '').trim()
}
console.log(removeClass(obj, 'open')); // obj.className='menu'
Also while working with DOM there are already methods for dooing this
const b = document.querySelector('button')
b.addEventListener('click', () => {
b.classList.remove('blue')
})
.red {
color: red
}
.blue {
color: blue
}
<button class="red blue">test</button>
Upvotes: 0