This creates an element with multiple classes. Take the following sample document below: The classList property is read-only by default, but it comes with supporting methods and properties that can be used to manipulate the list of classes assigned to an HTML element. Setter: Element.className = class (String) The classList property Note: The className property is destructive – if the element had a class before, it is now gone! The previous class information was replaced with the new “classy” value, and this will be the only class on the element. The output of this print will be “ classy” – the class we assigned on the fifth line of the script. Now that we’ve set the class value of the element, the second print statement will pick up the class value and print it to the console. The example above assigns the class “ classy” to the element obtained from the document. Applying the assignment operator turns the className property from a getter into a setter.
Where before the className property retrieved the class name for the element, we can repurpose it here to assign a class to the element.
#Javascript css html classes code
The second line of code (line 4) pulls in the first element found using the document.querySelector() method. Thus, the className property returns an empty string. In the above code, the first print to the console returns an empty string since the element has no class attribute when the code runs.
The expected output is an empty stringĭocument.querySelector('h1').className = 'classy' Ĭonsole.log(document.querySelector('h1').className) JavaScript console.log(document.querySelector('h1').className) Now let’s look at some sample JavaScript code that tries to manipulate this element: This code creates an element, but does not include the class. Take, for example, the following sample HTML code: You can access an element’s className by calling it directly on the element returned by a given querySelector. We generally recommend the second approach, using the classList property, as the resulting code is generally more readable, more accurate, and more functional than when modifying the className property directly.
#Javascript css html classes how to
Home > Tutorials > JavaScript > How to Set an HTML Element’s Class Using JavaScript JavaScript - How to Set an HTML Element’s Class Using JavaScript The HTML class attribute is used to mark individual elements with a class, distinguishing it from other elements in the document.