DevBoard Back to Desk

Blogs

Question-1: What are the different ways to select an element in the DOM?

We can select DOM elements in several ways:

  • document.getElementById('id') selects one element by its ID.
  • document.getElementsByClassName('class') selects elements by class name.
  • document.getElementsByTagName('tag') selects elements by tag name.
  • document.querySelector('selector') selects the first matching CSS selector.
  • document.querySelectorAll('selector') selects all matching CSS selectors.

Question-2: What is the difference between innerHTML, innerText, and textContent?

innerHTML gets or sets HTML markup, including tags. innerText returns the visible text and respects CSS styling. textContent returns all text inside the element, including hidden text, but does not read HTML tags as markup.

Question-3: What is event delegation in the DOM?

Event delegation means adding one event listener to a parent element instead of adding separate listeners to all its children. Because events bubble upward, the parent can use event.target to find which child was clicked. This is useful for dynamic elements and improves performance.

Question-4: What is event bubbling in the DOM?

Event bubbling is when an event starts on the element that was used and then moves upward through its parent elements. For example, clicking a button can also trigger click listeners on its card, section, and document unless propagation is stopped.

Question-5: How do you create, add, and remove elements using JavaScript?

Create an element with document.createElement('div'). Add it with parent.appendChild(element) or parent.append(element). Remove it with element.remove() or parent.removeChild(element).