Module - 2: DOM and JavaScript Answers
1. What is the Document Object Model (DOM)? Explain its significance in web
development.
• DOM stands for Document Object Model.
• It represents an HTML document as a tree structure.
• JavaScript uses the DOM to access and change web page elements.
• It helps developers change text, images, styles, and content dynamically.
• DOM makes web pages interactive.
• It allows event handling like clicks and keyboard actions.
2. Explain event delegation and how it improves performance in DOM manipulation.
• Event delegation means adding one event listener to a parent element instead of many child elements.
• It uses event bubbling.
• It improves performance because fewer event listeners are used.
• Memory usage becomes less.
• It works well for dynamically created elements.
• Example: Adding one click listener to a list instead of each list item.
3. Explain any six different DOM methods used to access or manipulate HTML elements.
• getElementById() – Selects an element using its id.
• getElementsByClassName() – Selects elements using class name.
• getElementsByTagName() – Selects elements using tag name.
• querySelector() – Selects the first matching CSS selector.
• querySelectorAll() – Selects all matching CSS selectors.
• createElement() – Creates a new HTML element.
4. How can you select HTML elements using JavaScript? Explain at least 3 methods.
• [Link]('id') – Selects element by id.
• [Link]('class') – Selects elements by class.
• [Link]('selector') – Selects the first matching CSS selector.
• [Link]('selector') – Selects all matching elements.
5. What are event listeners in JavaScript? How do they differ from traditional event
attributes?
• Event listeners wait for user actions like click or key press.
• They are added using addEventListener().
• Multiple listeners can be added to the same element.
• Traditional event attributes use HTML attributes like onclick.
• Event listeners separate JavaScript from HTML.
• They make code cleaner and easier to manage.
6. Explain an event and discuss the various types of events in JavaScript.
• An event is an action performed by the user or browser.
• Mouse events: click, dblclick, mouseover.
• Keyboard events: keydown, keyup.
• Form events: submit, change, focus.
• Window events: load, resize.
• Events help create interactive web pages.
7. Program: Create a button in HTML and add event listeners.
• HTML and JavaScript Example:
• <button id="btn">Click Me</button> <script> [Link]("btn").addEventListener("click",
function() { [Link]("Button clicked"); }); [Link]("keydown", function(event) {
[Link]("Key pressed: " + [Link]); }); </script>