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. 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. Modifying the classList property using its built-in methods.Modifying the className property (which serves both as a getter and setter).There are two straightforward ways to set an element’s class: Similarly, multiple HTML elements can share the same class – there is no restriction based on element type, and classes do not need to be unique. A single HTML element can have multiple classes. This allows front-end web developers to easily apply CSS styles to an element, or to easily identify and retrieve an element from the DOM. The HTML class attribute is used to mark individual elements with a class, distinguishing it from other elements in the document.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |