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:
newMine.classList.add(".mine");should benewMine.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).Elements that have
display: inlinedon't acceptheightorwidth. Usedisplay: inline-blockinstead.
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
