JavaScript DOM Concepts with Real Use Cases

1. Selecting Elements in JS

Definition: You can use various methods to select HTML elements dynamically:

Real Use Case: Selecting a product card when a user clicks "Add to Cart".

🛒 Product: JavaScript Course

const product = document.getElementById("product");
product.style.backgroundColor = "lightgreen";
    

2. Difference Between innerText, textContent, and innerHTML

innerText: Gets only visible text. It ignores hidden elements and formatting is affected by CSS.

textContent: Gets all text content, including hidden elements. It returns raw text without formatting.

innerHTML: Gets or sets the HTML content of an element, including tags, text, and even comments.

Real Use Case:

Welcome to My Blog! [Hidden SEO Content]

Subheading


    // Selecting the element
    const el = document.getElementById("textExample");
    
    el.innerText;     // Returns visible text only
    el.textContent;   // Returns all text (visible + hidden)
    el.innerHTML;     // Returns HTML string (with tags, comments, etc.)
      

3. setAttribute and getAttribute

Definition:

Real Use Case: Dynamically updating a link (e.g., user clicks "Visit Profile").

User Profile

link.setAttribute("href", "https://github.com/user");
link.getAttribute("href");
    

4. Change Styles Using classList

classList.add() adds a class, and classList.remove() removes it.

Real Use Case: Apply "active" or "highlighted" class on navigation or selection.

This paragraph's style will change on click.


para.classList.add("highlight");
para.classList.remove("highlight");
    

5. Access Parent and Sibling Elements

parentElement: Access the parent node of an element.

nextElementSibling / previousElementSibling: Navigate through adjacent elements.

Real Use Case: Form field validation: highlight the label (previous sibling) if input is empty.


const input = document.getElementById("emailInput");
const label = input.previousElementSibling;
const form = input.parentElement;