Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Tahsan's avatar

How to remove class name on javascript

I tried to remove child element class name but I'm not able to do right code.Can any one help me.

I tried bellow code structure-

html

<div id="items">
	<div class="item active">item-1</div>
	<div class="item ">tem-2</div>
	<div class="item ">tem-3</div>
</div>

script

document.getElementById('items').classList.remove("active");
0 likes
14 replies
Sinnbeck's avatar

classList just gets the classlist for the div with the id. Go over the child nodes.

document.getElementById('items').childNodes.forEach(e => e.classList.remove('active'))

Some older browser might not allow forEach one the nodeList

var children = document.getElementById('items').childNodes;
for (var i = 0; i < children.length; i++) {
    children[i].classList.remove('active')
}
Tahsan's avatar

Uncaught TypeError: e.classList is undefined

Sinnbeck's avatar

Ive added a version that should work on all browsers :)

ajithlal's avatar

what about

document.querySelector('#items').classList.remove('active');
Sinnbeck's avatar

You can test it in the console right on this page

var children = document.getElementById('root').childNodes;
for (var i = 0; i < children.length; i++) {
    if (children[i].classList) {
       children[i].classList.remove('xl:tw-flex-1')
    }
}
Tahsan's avatar

unfortunately, same error occurred

Sinnbeck's avatar

How is the error the same when there is no variable called e? Perhaps check if there is a classList like in my last example.

Tahsan's avatar

Uncaught TypeError: children[i].classList is undefined

Sam7745's avatar

getElementById("MyID"). className. replace(/\bMyClass\b/,''); where MyID is the ID of the element( https://www.njmc.website/ ) and MyClass is the name of the class you wish to remove.

Please or to participate in this conversation.