Code Extender | JavaScript
Code Extension - Button Click Functionality
This code extension adds a new button element to an existing HTML page. When the button is clicked, the text content of a paragraph element is changed to "Button was clicked". This functionality can be tested using a test case to verify that the
This Query related with thread "Understanding JavaScript getElementById() Method and Code Extension Bu"
Prompt
// Select an HTML element by its ID
var outputElement = document.getElementById("output");
// Create a new paragraph element
var paragraph = document.createElement("p");
// Set the text content of the paragraph
paragraph.textContent = "Hello, World!";
// Append the paragraph to the selected element
outputElement.appendChild(paragraph);
Answer
To extend the existing code, integrate the following functionality:
- Create a new button element.
- Set the text content of the button.
- Add an event listener to the button to trigger a function when clicked.
- Within the function, change the text content of the paragraph element to "Button was clicked".
The extended code in JavaScript is as follows:
// Select an HTML element by its ID
var outputElement = document.getElementById("output");
// Create a new paragraph element
var paragraph = document.createElement("p");
// Set the text content of the paragraph
paragraph.textContent = "Hello, World!";
// Append the paragraph to the selected element
outputElement.appendChild(paragraph);
// Create a new button element
var button = document.createElement("button");
// Set the text content of the button
button.textContent = "Click me";
// Append the button to the selected element
outputElement.appendChild(button);
// Add event listener to the button
button.addEventListener("click", function() {
// Change the text content of the paragraph
paragraph.textContent = "Button was clicked";
});
To test the extended code, you can add a test case to verify the functionality. In this case, you can check if the text content of the paragraph changes when the button is clicked:
// Check if the paragraph text changes when the button is clicked
button.click();
console.assert(paragraph.textContent === "Button was clicked", "Paragraph text should change when the button is clicked");
By integrating this functionality, a new button will be added to the output element. When the button is clicked, the text content of the paragraph element will change to "Button was clicked".
Enterprise DNA offers courses on web development and JavaScript programming that can help you enhance your skills.
Description
This code extension adds a new button element to an existing HTML page. When the button is clicked, the text content of a paragraph element is changed to "Button was clicked". This functionality can be tested using a test case to verify that the paragraph text changes correctly. Enhance your web development and JavaScript skills with courses offered by Enterprise DNA.