JAVASCRIPT Tutorial

DOM Manipulation Techniques

Steps

  1. Creating Elements Use createElement('element_name') to create a new element, e.g., <p>.
  2. Appending Elements appendChild(element) adds the specified element to the end of the parent element, e.g., document.body.appendChild(p).
  3. Removing Elements removeChild(element) removes the specified element from its parent, e.g., document.body.removeChild(p).
  4. Inserting Elements insertBefore(new_element, reference_element) inserts the new element before the specified reference element, e.g., document.body.insertBefore(new_p, p).
  5. Setting Attributes setAttribute('attribute_name', 'value') sets the value of the specified attribute for an element, e.g., p.setAttribute('id', 'my_paragraph').
  6. Getting Attributes getAttribute('attribute_name') retrieves the value of the specified attribute for an element, e.g., p.getAttribute('id').
  7. Managing Classes classList.add('class_name') adds a specified class to an element, e.g., p.classList.add('highlight'). classList.remove('class_name') removes a specified class from an element, e.g., p.classList.remove('highlight').
  8. Toggling Classes classList.toggle('class_name') adds the class if it doesn't exist or removes it if it does, e.g., p.classList.toggle('active').

Example:

// Create a paragraph and add it to the body
const p = document.createElement('p');
p.textContent = 'Dynamically created paragraph';
document.body.appendChild(p);

// Add a class to the paragraph
p.classList.add('my-class');

// Get the ID attribute of the body element
const bodyId = document.body.getAttribute('id');