Logo

DevBoard

Blogs

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


There are several methods to select elements in the DOM. We can use getElementById to target an element by its ID. Similarly, getElementsByClassName allows us to select elements by class, and getElementsByTagName can be used for tag names. For more advanced targeting, querySelector gives us the flexibility to use any CSS selector. If we need to select multiple elements, querySelectorAll is the way to go.

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


These three properties are often confused but serve different purposes. innerHTML gives us both the text and HTML content inside an element. innerText shows us only the visible text on the screen, ignoring hidden or off-screen content. textContent returns all the text in an element, including hidden text, but it strips away any HTML tags.

Question-3: How do you add an event listener in JavaScript?


We can add an event listener using the addEventListener method. For example, if we want to attach a click event to a button, we can do it like this: button.addEventListener('click', () => alert('Button clicked!')). This way, every time the button is clicked, the alert will be triggered.

Question-4: What is the purpose of the 'this' keyword in JavaScript?


The this keyword refers to the object that the function is associated with. Inside an object method, this points to the object itself. In regular functions, this usually refers to the global object. It helps us identify and access the context in which the code is being executed.

Question-5: How do you create a promise in JavaScript?


To create a promise, we use the Promise constructor, which takes a function with two parameters: resolve and reject. We call resolve when the task is successful, and reject when there's an error. This allows us to handle asynchronous tasks in a more structured way.