Chuck's Academy

DOM Manipulation in JavaScript

Manipulating Attributes and Properties

Once we have selected the DOM elements, the next step is to learn how to manipulate their attributes and properties. This skill allows us to modify the appearance and behavior of HTML elements dynamically.

Difference between Attributes and Properties

  • Attributes: These are part of the HTML tag and are defined directly in the HTML code. Examples include src, alt, class, id, etc.
  • Properties: These are representations in the DOM of the attributes, but they can have different values than those of the attributes in the HTML code. Properties also include characteristics not represented in HTML, such as innerText or value.

Manipulating Attributes

We can use the methods getAttribute, setAttribute, and removeAttribute to work with attributes.

getAttribute

This method retrieves the value of a specific attribute.

javascript

setAttribute

This method sets the value of an attribute.

javascript

removeAttribute

This method removes an attribute.

javascript

Manipulating Properties

Unlike attributes, properties are manipulated directly as JavaScript objects.

javascript

Manipulating Classes and Styles

Classes and styles can be considered both attributes and properties, but they are typically manipulated in specific ways.

Manipulating Classes

We can add, remove, or check if an element has a class using the classList properties.

javascript

Manipulating Styles

Inline styles can be manipulated directly using the style property.

javascript

Complete Example

Here is an example that combines various techniques for manipulating attributes and properties:

html

Conclusion

Manipulating DOM attributes and properties is a powerful tool that allows us to dynamically modify the content and appearance of our HTML elements. In the next chapter, we will explore how to modify the content and structure of the DOM in more detail.


Ask me anything