Ad

How To Have Access Inside Div Element?

- 1 answer

i am trying to create simple Rock,paper, scissor game, but i have some case, i want to have access on div which id is firstplayer, also this div has increment function, which increases value by 1... if in form field i choose 12, an when i press "firstplayer" and it value will increase to 12, i want to console.log("you win"), i tried a lot, but it's not works, what can i do, to solve this problem?

<!-----my html---->
<form action="#">
        <label for="numbers">Game up to:</label>
        <select id="form" >
          <option value="7" >7</option>
          <option value="12">12</option>
          <option value="15">15</option>
          <option value="20">20</option>
        </select>
        <input type="submit" id="submit">
      </form>
<div>
              <h4 onclick="increment()">Firstplayer</h4>
            <div id="firstplayer">

            </div>
          </div>

///my js
const firsPlayer = document.getElementById("firstplayer");
const Form = document.getElementById("submit");

form.addEventListener("input", function(event){
  event.preventDefault();
  if (event.target.value==="12"){ 
   return playerwin()
  }
})

var x=0;
function increment(){
   return firsPlayer.innerHTML = ++x;
}

// i tried this but it's not working
function playerwin(){   
         if(firsPlayer.childNodes[0].nodeValue == 12){
            console.log("you win")
         }
}



my code here https://codepen.io/kafka2001/pen/LYpmexe

Ad

Answer

Not exactly sure what the final result should be but please check the code below that illustrates how it could basically work. Just adapt it to your needs to obtain the desired result.

const firsPlayer = document.getElementById("firstplayer");
const select = document.getElementById("select");
var x = 0;

function increment() {
  firsPlayer.innerHTML = Number(firsPlayer.innerHTML) + 1;
}

function addSelected() {
  firsPlayer.innerHTML = Number(firsPlayer.innerHTML) + Number(select.value);
}

function playerwin() {
  if (firsPlayer.childNodes[0].nodeValue == 12) {
    console.log("you win")
  }
}
<select id="select">
  <option value="7">7</option>
  <option value="12">12</option>
  <option value="15">15</option>
  <option value="20">20</option>
</select>
<input type="button" onClick="increment();" value="Increment">
<div>
  <h4 onclick="addSelected()">Firstplayer</h4>
  <div id="firstplayer"></div>
</div>

Ad
source: stackoverflow.com
Ad