Sometimes, we want to remove the first character of a class name with JavaScript.
In this article, we’ll look at how to remove the first character of a class name with JavaScript.
How to remove the first character of a class name with JavaScript
To remove the first character of a class name with JavaScript, we can use the string’s substring method.
For instance, we write:
<div class='foo'>
</div>
to add a div with a class attribute set.
Then we write:
const div = document.querySelector('div')
const trimmed = div.className.substring(1);
console.log(trimmed)
to select the div with querySelector.
Then we get the class name with className.
And then we call substring with 1 to return the class name string without the first character.
Therefore trimmed is 'oo'.
Conclusion
To remove the first character of a class name with JavaScript, we can use the string’s substring method.