+ 2

Why can't I change value of class attribute like this: document.getElementById("demo").class="hello";?

I know about setAttribute() method, but still you can change other attributes value (for eg:- src attribute value in image) by above method but not the class attribute value. Did I do anything wrong in above method?

26th Jun 2018, 8:19 AM
Prathamesh Sawant
Prathamesh Sawant - avatar
3 Answers
+ 2
GET/SETATTRIBUTE methods get/setAttribute() mostly deprecated now. There are existing DOM attributes for directly accessing almost every HTML element attribute. CLASSNAME attribute For starters, direct assignment to an element's class uses the "className" DOM attribute, not "class". Direct assignment overwrites any other classes already assigned to that element (which might be what you want). If you instead want to append, you can use element.className += " class" (space at start of string important) to add on to existing string. However checking if an element contains a particular class or removing a class is more troublesome for "className" and multiple classes. CLASSLIST attribute - BETTER WAY ADDED IN HTML5 "classList" DOM attribute treats the element's space delimited class string as an array where each element is a string value. "classList" has several very useful built-in methods such as add(), remove(), contains(), toggle(), length, and toString(). These make it very easy to add/remove/status-check classes on elements with multiple classes (likely if using frameworks like Bootstrap). document.getElementById("demo").className="hello"; could be replaced with (if overwrite not desired) document.getElementById("demo").classList.add("hello"); or document.getElementById("demo").classList.toggle("hello", true);
3rd Jul 2018, 4:14 AM
Shardis Wolfe
+ 1
Try this Because class can be multiple so it becomes array document.getElementById('demo' ). classList.add("hello");
26th Jun 2018, 8:44 AM
áŽ‹á”˜âżá”ƒËĄ
áŽ‹á”˜âżá”ƒËĄ - avatar
+ 1
From Stackoverflow: "To change all classes for an element: To replace all existing classes with one or more new classes, set the className attribute: document.getElementById("MyElement").className = "MyClass"; (You can use a space-delimited list to apply multiple classes.)" Longer explanation here: https://stackoverflow.com/questions/195951/change-an-elements-class-with-javascript
26th Jun 2018, 9:08 AM
Janning⭐
Janning⭐ - avatar