{"id":12260,"date":"2022-08-03T12:28:05","date_gmt":"2022-08-03T16:28:05","guid":{"rendered":"http:\/\/local.brightwhiz\/?post_type=snippets&p=12260"},"modified":"2022-08-03T12:28:08","modified_gmt":"2022-08-03T16:28:08","slug":"add-class-to-html-element-using-vanilla-javascript","status":"publish","type":"snippets","link":"http:\/\/local.brightwhiz\/snippets\/add-class-to-html-element-using-vanilla-javascript\/","title":{"rendered":"How to Add a Class to an HTML Element Using Vanilla JavaScript"},"content":{"rendered":"\n
If you have an HTML element like this.<\/p>\n\n\n\n
<div id="element"><\/div><\/code><\/pre>\n\n\n\nYou can add or remove classes with similar JavaScript code.<\/p>\n\n\n\n
var element = document.getElementById('element');\nelement.classList.add('class-1');\nelement.classList.add('class-2', 'class-3');<\/code><\/pre>\n\n\n\nThis would be the result.<\/p>\n\n\n\n
<div id="element" class="class-1 class-2 class-3"><\/div><\/code><\/pre>\n\n\n\nRemove a class.<\/p>\n\n\n\n
element.classList.remove('class-3');<\/code><\/pre>\n\n\n\nThis is after removing once of the classes.<\/p>\n\n\n\n
<div id="element" class="class-1 class-2"><\/div><\/code><\/pre>\n","protected":false},"comment_status":"open","ping_status":"closed","template":"","meta":[],"categories":[953,27,15,16],"tags":[303,328,424,471,638],"yoast_head":"\nAdd a Class to HTML Element Using Vanilla JavaScript Snippet<\/title>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n