Learn how to interact with HTML elements and respond to user actions using JavaScript.
Example demonstrating event handling and DOM manipulation:
// Select button and paragraph elements
const button = document.getElementById('myButton');
const paragraph = document.getElementById('myParagraph');
// Add a click event listener to the button
button.addEventListener('click', () => {
// Change the paragraph text and style on button click
paragraph.textContent = "You clicked the button!";
paragraph.style.color = 'blue';
});
This code demonstrates:
getElementById
.DOM (Document Object Model): The DOM is a programming interface for HTML documents. It represents the page so that programs can change the document structure, style, and content.
Events: Events are actions or occurrences that happen in the system, such as user interactions like clicks, key presses, or page loads. JavaScript can listen to these events and execute code in response.
Event Listeners: Functions that are called when an event occurs on a target element. They can be attached using methods like addEventListener
.
DOM Manipulation: Involves changing the elements, attributes, and styles of the HTML document dynamically using JavaScript.
getElementById
, querySelector
.textContent
, innerHTML
.style
property.Q1: Which method is used to attach an event listener to an element?
addEvent()
addListener()
addEventListener()
attachEvent()
Answer: C. addEventListener()
Q2: What does document.getElementById('id')
do?
Answer: C. Selects the element with the specified ID.
Q3: Which property changes the text content of an HTML element?
innerText
textContent
innerHTML
Answer: D. All of the above
Q4: How do you change the color style of a paragraph with id "para"?
document.getElementById('para').style.color = 'red';
document.getElementById('para').color = 'red';
document.getElementById('para').setColor('red');
document.getElementById('para').textColor = 'red';
Answer: A. document.getElementById('para').style.color = 'red';