JavaScript Fundamentals

DOM Manipulation

Understanding DOM Manipulation

The Document Object Model (DOM) is a programming interface for HTML documents. It represents the page as a tree of objects that you can modify with JavaScript. Learning DOM manipulation is essential for creating interactive web applications.

Selecting Elements

// Selecting Elements
// By ID
const element = document.getElementById('myId');

// By Class Name
const elements = document.getElementsByClassName('myClass');

// By Tag Name
const divs = document.getElementsByTagName('div');

// Using Query Selector
const firstMatch = document.querySelector('.myClass');
const allMatches = document.querySelectorAll('.myClass');

Modifying Elements

// Modifying Elements
// Changing Text Content
element.textContent = 'New Text';
element.innerHTML = '<span>HTML Content</span>';

// Modifying Attributes
element.setAttribute('class', 'newClass');
element.classList.add('active');
element.classList.remove('inactive');
element.classList.toggle('visible');

// Changing Styles
element.style.color = 'blue';
element.style.backgroundColor = '#f0f0f0';
element.style.display = 'none';

Event Handling

// Event Handling
// Click Event
element.addEventListener('click', function(event) {
  console.log('Element clicked!');
  event.preventDefault(); // Prevent default behavior
});

// Form Events
form.addEventListener('submit', function(event) {
  event.preventDefault();
  const formData = new FormData(form);
  console.log(formData.get('username'));
});

// Keyboard Events
document.addEventListener('keydown', function(event) {
  console.log(`Key pressed: ${event.key}`);
});

Creating and Removing Elements

// Creating and Removing Elements
// Create Element
const newDiv = document.createElement('div');
newDiv.textContent = 'New Element';
newDiv.classList.add('new-class');

// Append Element
parentElement.appendChild(newDiv);

// Insert Before
parentElement.insertBefore(newDiv, referenceElement);

// Remove Element
element.remove();
// Or
parentElement.removeChild(element);