DevBoard

Blogs

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

We can grab elements in different ways depending on what we need. If an element has an ID, we use getElementById(). For classes and tags, getElementsByClassName() or getElementsByTagName() work. But the most flexible options are querySelector() (for the first match) and querySelectorAll() (for all matches).

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

innerHTML gives us everything inside an element, including HTML tags. innerText only gets the visible text, ignoring hidden elements. textContent grabs all the text, whether it’s visible or not. If we're dealing with raw text, textContent is usually the safer option.

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

Instead of adding event listeners to a bunch of individual elements, we can attach one listener to a parent element and let events "bubble up" from its children. This makes our code more efficient, especially for dynamic elements.

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

Event bubbling means that when we click on an element, the event doesn’t just stay there—it moves up through its parent elements too. So if we click a button inside a div, both the button and the div can react unless we stop the event from bubbling up.

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

First, we create an element using document.createElement(). Then, we attach it to the page with appendChild() or insertBefore(). If we need to remove it, we use removeChild() or element.remove(). Simple as that!