Definition: You can use various methods to select HTML elements dynamically:
getElementById() - selects a single element by IDgetElementsByClassName() - selects a collection by classquerySelector() - selects the first match by CSS selectorquerySelectorAll() - selects all matches by CSS selectorReal Use Case: Selecting a product card when a user clicks "Add to Cart".
const product = document.getElementById("product");
product.style.backgroundColor = "lightgreen";
innerText, textContent, and innerHTMLinnerText: 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:
innerText: When you want only what the user can currently see on the screen.textContent: When you want all textual content, regardless of visibility (e.g., scraping,
SEO).
innerHTML: When you want to get/set formatted content or inject actual HTML code into the
DOM.
// 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.)
setAttribute and getAttributeDefinition:
setAttribute(attr, value) sets a new or updates an attribute.getAttribute(attr) retrieves the value of an attribute.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");
classListclassList.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");
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;