💻

DOM Manipulation Techniques

Jul 11, 2024

DOM Manipulation Techniques

Introduction

  • DOM manipulation involves numerous techniques, but only 14 key ones are necessary to master.
  • Objective: To simplify web development for building dream projects faster.
  • Tools: A blank HTML file linked to a script file.

Adding Elements

Selecting the Element

  • Select the element, e.g., the body, using document.body.

Using append and appendChild

  • body.append('Hello World'): Directly appends strings and multiple elements.
  • body.appendChild(element): Appends only one DOM node at a time.
  • Recommendation: Use append for its versatility.

Creating Elements

  • Use document.createElement('div') to create elements.
  • Append created elements using append method to add to the DOM.

Modifying Text

innerText vs. textContent

  • Both methods set text inside an element.
  • innerText: Considers CSS visibility, rendering only visible text.
  • textContent: Ignores CSS visibility, includes all text and spacing.

Adding HTML

  • Use innerHTML to insert HTML content within elements (e.g., <strong>Hello</strong>).
  • Caution: Security risks. Prefer creating elements via document.createElement for user-provided content.

Removing Elements

Methods

  • element.remove(): Directly removes the element from the DOM.
  • parentElement.removeChild(element): Removes the specified child from its parent node.
  • Recommendation: Use remove() for simplicity.

Attribute Manipulation

Getting and Setting Attributes

  • element.getAttribute('id') and element.id: Retrieves the attribute value.
  • element.setAttribute('id', 'newId') and element.id = 'newId': Sets new attribute values.
  • Recommendation: Use element properties (like .id, .title) when available.

Removing Attributes

  • element.removeAttribute('title'): Removes specified attribute.

Working with Data Attributes

  • Data attributes use data- prefix (e.g., data-test).
  • Accessed through element.dataset (e.g., element.dataset.test).
  • Automatically handles conversion between CamelCase (in JavaScript) and kebab-case (in HTML).

Manipulating Classes

  • Use element.classList to manipulate class attributes.
  • Methods:
    • add(className): Adds a class.
    • remove(className): Removes a class.
    • toggle(className): Adds/removes class based on its presence.
    • toggle(className, boolean): Adds/removes class based on the boolean value.

Styling Elements

  • Directly modify CSS properties using element.style.propertyName.
  • Conversion to camelCase for CSS properties with hyphens (e.g., backgroundColor for background-color).

Conclusion

  • For advanced learning, refer to the full JavaScript course.
  • Course link provided for further materials and sign-up.