DOM Manipulation

1. DOM Structure

The DOM represents the HTML document as a tree of nodes.

  • Document: Entry point of the DOM.
  • Element Nodes: Represent HTML elements.
  • Text Nodes: Contain the text inside elements.
  • Attribute Nodes: Represent HTML attributes.
  • Comment Nodes: Represent comments.

2. Selecting Elements

Single Element Selectors

  • document.getElementById('id')
  • document.querySelector('selector')

Multiple Element Selectors

  • document.getElementsByClassName('class')
  • document.getElementsByTagName('tag')
  • document.querySelectorAll('selector')

// Examples:
const title = document.getElementById('main-title');
const items = document.querySelectorAll('.list-item');

3. Traversing the DOM

  • parentNode / parentElement
  • childNodes / children
  • firstChild / firstElementChild
  • lastChild / lastElementChild
  • nextSibling / nextElementSibling
  • previousSibling / previousElementSibling

const list = document.querySelector('ul');
console.log(list.children[0].textContent); // First child

4. Manipulating Content

Text & HTML

  • element.textContent – gets/sets text content
  • element.innerText – similar to textContent but rendered text
  • element.innerHTML – gets/sets HTML inside an element

const header = document.getElementById('header');
header.textContent = "New Heading";
header.innerHTML = "<span>Updated</span>";

5. Manipulating Attributes

  • element.getAttribute('name')
  • element.setAttribute('name', 'value')
  • element.removeAttribute('name')
  • element.hasAttribute('name')

const link = document.querySelector('a');
link.setAttribute('href', 'https://example.com');

6. Styling Elements

Inline Styles


element.style.color = "red";
element.style.fontSize = "20px";

Class Manipulation

  • element.classList.add('class')
  • element.classList.remove('class')
  • element.classList.toggle('class')
  • element.classList.contains('class')

element.classList.add('active');

7. Creating and Inserting Elements


// Create new element
const newDiv = document.createElement('div');
newDiv.textContent = "I am new!";

// Append to body
document.body.appendChild(newDiv);

// Insert before another element
const container = document.getElementById('container');
container.insertBefore(newDiv, container.firstChild);

8. Removing Elements


const element = document.getElementById('to-remove');
element.remove(); // modern way

// older way
element.parentNode.removeChild(element);

9. Event Handling

Events are actions that happen in the browser (e.g. clicks, key presses). JavaScript can respond using event listeners.


// Method 1: Inline HTML (not recommended)
// <button onclick="alert('Clicked!')">Click Me</button>

// Method 2: addEventListener (preferred)
const btn = document.querySelector('button');
btn.addEventListener('click', function() {
  alert('Button clicked!');
});

Common Events

  • click
  • mouseover, mouseout
  • keydown, keyup, keypress
  • submit
  • change, input

10. DOMContentLoaded Event


document.addEventListener('DOMContentLoaded', function() {
  console.log('DOM fully loaded');
});

11. Best Practices

  • Always wait for the DOM to load before accessing elements.
  • Use addEventListener instead of inline events.
  • Use class manipulation instead of inline styles for maintainability.
  • Cache DOM queries if reused to improve performance.

12. Useful Methods Summary

Method Description
createElement() Creates a new element
appendChild() Adds a child node to a parent
removeChild() Removes a child node
replaceChild() Replaces one child node with another
cloneNode() Clones a node (deep or shallow)

JavaScript Function

1. What will be the output of the following code?


            const header = document.getElementById('header');
            console.log(header);
            

2. What will be the output of the following code?


            const firstButton = document.querySelector('.button');
            console.log(firstButton);
            

5. What will be the output of the following code?


            const div = document.getElementById('myDiv');
            div.innerHTML = '<p>New content</p>';
            console.log(div.innerHTML);
            

6. What will be the output of the following code?


            const newDiv = document.createElement('div');
            console.log(newDiv);
            

7. What will happen when the following code is executed?


    const list = document.getElementById('myList');
    const newItem = document.createElement('li');
    newItem.textContent = 'New Item';
    list.appendChild(newItem);
    console.log(list);
    

8. What will be the output of the following code?


    const img = document.querySelector('img');
    img.setAttribute('src', 'image.png');
    console.log(img.src);
    

9. What will be the output of the following code?


    const box = document.getElementById('box');
    console.log(box.classList);
    

10. What will be the output of the following code?


    const button = document.querySelector('.button');
    button.addEventListener('click', (e) => {
        e.stopPropagation();
        console.log('Button clicked');
    });
    

11. What will be the output of the following code?


    const textNode = document.createTextNode('Hello World');
    console.log(textNode);
    

12. What will be the output of the following code?


    const original = document.getElementById('myElement');
    const clone = original.cloneNode(true);
    console.log(clone);
    

13. What will be the output of the following code after 2 seconds?


    setTimeout(() => {
        console.log('Hello after 2 seconds');
    }, 2000);
    

14. What will happen when the following code is executed on a form submission?


    const form = document.querySelector('form');
    form.addEventListener('submit', (e) => {
        e.preventDefault();
        console.log('Form submission canceled');
    });
    

15. What will happen when the following code is executed?


    const box = document.getElementById('box');
    box.classList.toggle('active');
    console.log(box.classList);
    

16. What will be the output of the following code?


    const container = document.getElementById('container');
    container.innerHTML = '

Updated Content

'; console.log(container.innerHTML);

17. What will be the output of the following code?


    const items = document.querySelectorAll('.item');
    console.log(items.length);
    

18. What will be the output of the following code?


    const arr = ['a', 'b', 'c', 'd'];
    const sliced = arr.slice(1, 3);
    console.log(sliced);
    

19. What will happen when the following code is executed?


    const input = document.querySelector('input');
    input.addEventListener('input', () => {
        console.log('Input changed');
    });
    

20. What will be the output of the following code?


    const numbers = [1, 2, 3];
    numbers.forEach(num => console.log(num * 2));
    

Post a Comment

Your comment will be visible after approval.
© TechTestLog. All rights reserved. Premium By Raushan Design
//My script