...

/

DOM Attributes and Styling

DOM Attributes and Styling

Learn about getting and setting attributes with DOM methods, as well as styling.

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 ...