Having issues making div elements with javascript

I am having trouble generating new divs when a specific div is clicked. Despite my efforts, nothing seems to be happening and the console isn't showing any errors. I've searched online for solutions but haven't found anything that addresses my issue. Any assistance on this matter would be greatly appreciated.

HTML

<!DOCTYPE html>
<html>
    <head>
        <title>
        Space Invaders
        </title>
        <script type = 'text/javascript' src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'></script>
        <link href="style.css" rel="stylesheet" type="text/css" />
        <script src="script.js" type="text/javascript">               </script>
    </head>
    <body>
    <div>
        <div id="startbtn"><br />Start Game
        </div>
        <br />
        <center>
        <div id="game" onClick = 'buttonClick'>
        </div>
        <div id="game2">
        </div>
        </center>
        <div id="titlepage">
        </div>
    </div>
    </body>
</html>

CSS

#startbtn
{
    height: 60px;
    width: 100px;
    border-radius: 5px;
    background-color: #69D2E7;
    text-align: center;
    color: #000000;
    font-family: Arial;
    opacity: 0.5;
    margin: auto;
}
#game { 
    display: none;
    margin: auto;
}
#game2
{ 
    display: none;
    margin: auto;
}
#grid {
    display: inline-block;
    background-color: #000000;
    width: 20px;
    height: 20px;
    border-radius: 2px;
}

JavaScript

var row1 = [];
$(document).ready(function() 
{
    $('#startbtn').click(function(){
        for (var i = 0; i<9; i++)
    {
        row1[i] = document.createElement('div');
        row1[i].id = 'grid';
        document.getElementById('game').appendChild(row1[i]);
        }
    }   
    });
});

Answer №1

for (var i = 0; i<9; i++)
{
    row1[i] = document.createElement('div');
    row1[i].id = 'grid' + i;

The id attribute must be unique within the document. It is not possible to create 9 divs with the same id of grid.

Answer №2

In order to ensure unique identifiers, a simple solution is to incorporate a count variable into the ID:

    for (var i = 0; i<9; i++)
    {
        row1[i] = document.createElement('div');
        row1[i].id = 'grid' + i;
        document.getElementById('board').appendChild(row1[i]);
    }

UPDATE

I understand what may have caused some confusion. You intended to assign the same ID of grid to all div elements for consistent styling, which was influenced by your CSS definition of #grid.

The better approach would be to utilize CSS classes. Modify the CSS rule from #grid to .grid, and then apply this class to each generated div element (ensuring each ID remains unique):

    for (var i = 0; i<9; i++)
    {
        row1[i] = document.createElement('div');
        row1[i].id = 'grid' + i;
        row1[i].className = 'grid';
        document.getElementById('board').appendChild(row1[i]);
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to obtain an attribute through random selection

Figuring out how to retrieve the type attribute from the first input element: document.getElementById('button').addEventListener('click', function() { var type = document.querySelectorAll('input')[0].type; document.getE ...

html how to delete the beginning and end of hr element

There is a <hr noshade> tag in my HTML code which does not have any effect on the web view. However, when I print it to a PDF file, it shows head and tail like this: https://i.stack.imgur.com/TaBAc.jpg Here is my CSS that applies styling when print ...

Storing dynamic content on a server and retrieving it for future use

I'm working on a webpage that allows users to create elements dynamically and I want to save those elements to the server. When someone else visits the page, I want them to see those saved elements as well. I'm not too familiar with web programm ...

Issue - Following error occurred in the file connection.js located in node_modules/mysql2 library: Module not found: Unable to locate 'tls' module

I've encountered an error in our Next JS applications where tls is not found. I have tried several troubleshooting steps including: 1. Updating Node modules 2. Using both mysql and mysql2 3. Running npm cache clean --force 4. Removing node_modules di ...

How can you attach an event handler to an HTML button without disrupting its default behavior?

I am working on enhancing a contact form to include a feature where the submit button becomes disabled for five seconds after it is clicked. This is to prevent accidental repeat submissions from occurring. However, I am facing an issue where disabling the ...

How can I monitor an input field that already has a value in Vue?

My current setup includes an email input and a watcher that verifies if the input is valid or not. The issue I'm facing is that the watch event only triggers when something new is typed into the email field. This means that if the existing value in th ...

Using jQuery AJAX to apply filters to forms and update URL hashes

I have coded the following snippets: <label class='checkbox'><input type='checkbox' class='custom_filter' name='kleuren' value='Blauw' data-taxonomy='kleuren' data-category='Bla ...

Implementing specifications throughout the entire nodejs route

In my Nodejs app, I have a RESTful API where I need to check for a user's role before sending a response with data or 404 error. apiRouter.route('/users') .get(function (req, res) { var currentUser = req.decoded; if(curr ...

Issues with React router arise once the app has been built

I am new to utilizing react and react-router in my project. I have built the application using create-react-app and now I am facing an issue with routing between two main pages. After trying different approaches, I managed to get it working during develop ...

Concealing Contact Form Using Javascript

Upon making adjustments to a website, I encountered an issue with the contact form. The form is meant to be hidden on page load and only appear when the envelope icon is clicked. However, currently the form is visible by default, and clicking the envelope ...

What is the reason for not displaying the various li elements on my webpage?

Here is the code snippet export default function DisplaySearchResults({ results }) { var arr = Object.entries(results) console.log(arr) return ( <div> Here are the search results : <ol> {arr.map((va ...

Files on video input are now accepting audio attribute

Currently, I am adding a file upload feature to my application. I have created input fields for various types of media. <label>Images<input type="file" accept="image/*"/></label> <label>Videos<input type="file" accept="video/*"/ ...

Checkbox values are not being properly returned in the AJAX post request

var selectedValues = $('input:checkbox:checked').map(function() { return this.value; }).get(); $.ajax({ type: 'POST', url: 'showdata.php', data: {values : selectedValues}, success: function(response) { // Only t ...

Can Vue.js support two-way data-binding without the use of an input element?

Here is the code snippet that I'm working with: <div id="app"> {{ message }} </div> JavaScript: myObject = {message:"hello"} new Vue({ el: '#app', data: myObject }) When I update myObject.message, the content within th ...

adjusting the size and positioning of an image within a parent div using React

Hey everyone, I'm a newcomer to the world of React. Currently, I'm working on a website and everything seems to be falling into place nicely. However, I've encountered a little hiccup. My goal is to write code within my SCSS folder that will ...

Discover the method for storing multiple values in local storage using a dictionary with JavaScript

I have a scenario in my code where I need to update a value without storing a new one. Let's say I need to input values in the following format: { firstname:'kuldeep', lastname:- 'patel' } After entering the values, they g ...

Guide to utilizing Terser in conjunction with webpack

I am currently using Webpack 6.10.2 in combination with Vue 3.9.3. I encountered an issue with Uglify.js when running npm run build due to its inability to handle ES6 code. To work around this problem, I followed the recommendation of removing Uglify fro ...

Steps to align the table to the left with the header

I created a webpage that includes a header and a table at this link Can anyone help me align the left border of the table with the left border of the header image? I'm not sure how to do it. Appreciate any assistance! ...

Position a div element on top of Google Maps to create a floating

Currently working on a website and attempting to add shadows over Google Maps by using a <div> element for a shadow effect: Unfortunately, the desired effect is not being achieved. This is the current CSS code in use: html { height: 100% } body ...

Substituting HTML checkboxes with highlighted images for consistent display across different web browsers

I am looking to transform a list of HTML checkboxes into clickable images for the user to select or deselect. My goal is to create a similar functionality as shown in this video using just CSS if possible. I have successfully implemented it in Chrome wit ...