DEV Community

Ranjith srt
Ranjith srt

Posted on

js - DOM

Introduction to JavaScript DOM
DOM (Document Object Model): It represents the HTML document structure in a tree-like format. Each element in the HTML becomes a node in the DOM.
Importance: DOM allows JavaScript to interact with and manipulate the structure, style, and content of a webpage.

1. Selecting DOM Elements document.


Methods to select elements:

document.getElementById('id');  // Selects an element by its id

document.getElementsByClassName('class');  // Selects all elements with the specified class

document.getElementsByTagName('tag');  // Selects all elements with the specified tag

document.querySelector('selector');  // Selects the first element that matches a CSS selector

document.querySelectorAll('selector');  // Selects all elements matching a CSS selector

Enter fullscreen mode Exit fullscreen mode

2. Manipulating Elements


//Changing content 

element.textContent = 'new content';  // Changes the text inside an element

element.innerHTML = '<p>new HTML</p>';  // Inserts HTML into an element

// Modifying attributes

element.setAttribute('attribute', 'value');  // Sets an attribute's value

element.getAttribute('attribute');  // Retrieves the value of an attribute

element.removeAttribute('attribute');  // Removes an attribute


// Styling elements

element.style.property = 'value';  // Changes an element's inline CSS

Enter fullscreen mode Exit fullscreen mode

3.Working with Classes


Adding/Removing/Toggling classes:

element.classList.add('className');  // Adds a class to an element

element.classList.remove('className');  // Removes a class from an element

element.classList.toggle('className');  // Toggles a class on or off


Enter fullscreen mode Exit fullscreen mode

4.Creating and Removing Elements


// Creating elements

let newDiv = document.createElement('div'); 

// Creates a new div element

element.appendChild(newDiv);  // Adds a new element to the DOM

element.insertBefore(newElement, referenceElement);  // Inserts an element before another

// Removing elements

element.remove();  // Removes an element from the DOM

parent.removeChild(child);  // Removes a child element from its parent

Enter fullscreen mode Exit fullscreen mode

5.Event Handling


// Adding events

button.addEventListener('click',function() {
    alert('Button clicked!');
});

// Removing events

button.removeEventListener('click', eventHandler);


Common event types:

click, mouseover, mouseout, keydown, keyup, load, scroll, etc.

Enter fullscreen mode Exit fullscreen mode

6.Event Object and Delegation


// Event Object

element.addEventListener('click',function(event) {

  console.log(event.target);  // Logs the clicked element
});

// Event Delegation

parentElement.addEventListener('click', function(event) {
    if (event.target.classList.contains('childClass')) {
        console.log('Child clicked!');
    }
});

Enter fullscreen mode Exit fullscreen mode

7.Forms and Input


let form = document.forms['formName'];  // Accessing a form by name

let input = form.elements['inputName'];  // Accessing an input field by name

console.log(input.value);  // Retrieving the input value

Enter fullscreen mode Exit fullscreen mode

8.Local Storage & Session Storage


//Local Storage

localStorage.setItem('key', 'value');  // Stores data

let value = localStorage.getItem('key');  // Retrieves stored data

localStorage.removeItem('key');  // Deletes stored data

localStorage.clear();  // Clears all stored data

// Session Storage

sessionStorage.setItem('key', 'value');  // Stores data for the session

let sessionValue = sessionStorage.getItem('key');
  // Retrieves session data

sessionStorage.removeItem('key');  // Deletes session data

sessionStorage.clear();  // Clears all session data

Enter fullscreen mode Exit fullscreen mode

9. Fetching Data with Async/Await



// Fetching data from an API using Promises

fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => console.log(data));

// Using async/await for fetching data. 

async function fetchData() {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    console.log(data);
}

fetchData();

Enter fullscreen mode Exit fullscreen mode

Top comments (0)