You are a developer. You need to solve the following problem: You have 3 empty DIVs. You…
- User
You are a developer. You need to solve the following problem: You have 3 empty DIVs. You need to populate each div with consecutive numbers.
- Assistant
To solve the problem of populating three empty DIVs with consecutive numbers, you can use a simple JavaScript function that assigns numbers to each DIV. Here's a basic example of how you can achieve this:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Populate DIVs with Numbers</title> </head> <body> <div id="div1"></div> <div id="div2"></div> <div id="div3"></div> <script> // Function to populate DIVs with consecutive numbers starting from a given number function populateDivs(startNumber) { // Get the DIV elements by their IDs const div1 = document.getElementById('div1'); const div2 = document.getElementById('div2'); const div3 = document.getElementById('div3'); // Populate each DIV with consecutive numbers div1.textContent = startNumber; div2.textContent = startNumber + 1; div3.textContent = startNumber + 2; } // Call the function with the starting number populateDivs(1); </script> </body> </html>Explanation:
-
HTML Structure: There are three empty DIV elements with IDs
div1,div2, anddiv3. -
JavaScript Function: The function
populateDivstakes astartNumberas an argument and populates each DIV with consecutive numbers starting fromstartNumber. -
DOM Manipulation:
document.getElementByIdis used to get each DIV element by its ID. ThetextContentproperty is then used to set the content of each DIV to the appropriate number. -
Function Call: Finally, the function is called with a starting number. In this example, it starts with 1, which populates the DIVs with 1, 2, and 3.
You can modify the
startNumberargument when callingpopulateDivsto start with a different number. -