Home > Net >  How to Add Element Created in JavaScript File to HTML page
How to Add Element Created in JavaScript File to HTML page

Time:01-08

I am attempting a create an element in the js file which will then be added to the html div where the game is

I am trying to make a createMine function that creates a new element with the style in .mine and then adds it the the html game div.

var newMine = document.createElement("div");
newMine.classList.add(".mine");
document.getElementById("game").appendChild(newMine);
.mine {
  width: 20px;
  height: 20px;
  background-color: blue;
  position: relative;
  display: inline;
}
<div id="game">
  <button id="startButton">Click To Start</button>
  <div id="gameElements">
    <div id="character">
    </div>
  </div>
</div>

CodePudding user response:

Your code is working properly except two problems:

  1. newMine.classList.add(".mine"); should be newMine.classList.add("mine"); (don't use the . when adding the class, its only purpose is to tell CSS that the following is a CSS class).

  2. Elements that have display: inline don't accept height or width. Use display: inline-block instead.

CodePudding user response:

var newMine = document.createElement("div");
newMine.classList.add("mine");
document.getElementById("game").appendChild(newMine);
.mine{
    width: 20px;
    height: 20px;
    background-color: blue;
    position: relative;
    display: inline-block;
}
<div id="game">
    <button id="startButton">Click To Start</button>
    <div id="gameElements">
        <div id="character"></div>
    </div>
</div>

when using classlist, don't write a dot at the beginning to make it work it works. and as @connexo said, use inline-block

  •  Tags:  
  • Related