Search⌘ K

DOM Attributes and Styling

Explore how to manipulate DOM attributes and CSS styles dynamically in JavaScript. Learn to get and set attributes, efficiently manage classes with classList, and update element styles using the style property. Understand best practices for styling elements by toggling classes to keep code clean and flexible.

Getting and setting attributes

All HTML elements have a large number of possible attributes, such as class, id, src, and href. The DOM has a number of methods that can be used to get or set these attributes.

Getting an element’s attributes

The getAttribute() method returns the value of the attribute provided as an argument. For example, we can find out the class of the apple element by entering the following code into the console:

If an element doesn’t have the given attribute, it returns null. For example, if we enter the following code into the console, we can see that the broccoli element doesn’t have a src attribute (we didn’t add one when we created the element earlier):

Setting an element’s attributes

The setAttribute() method can change the value of an element’s attributes. It takes two arguments: the attribute that we wish to change and the new value of that attribute.

For example, if we want to add the class of veg to the ...