Как мне добавить сгенерированную в JS кнопку в div вместо тела

#javascript #html #css

#javascript #HTML #css

Вопрос:

Привет 🙂 Я пытаюсь немного угадать игру с числами в JS, чтобы я мог, наконец, выучить этот язык, и, несмотря на то, что функциональность выполнена, у меня есть некоторые проблемы с добавлением кнопки, сгенерированной JS, в div контейнера вместо тела.

 let randomNumber = Math.floor(Math.random() * 100)   1;

const guesses = document.querySelector(".guesses");
const lastResult = document.querySelector(".lastResult");
const lowOrHi = document.querySelector(".lowOrHi");

const guessField = document.querySelector(".guessField");
const guessSubmit = document.querySelector(".guessSubmit");

let guessCount = 1;
let resetButton;
guessField.focus();

function checkGuess() {
  let userGuess = Number(guessField.value);
  if (guessCount === 1) {
    guesses.textContent = "Previous guesses: ";
  }
  guesses.textContent  = userGuess   " ";

  function setGameOver() {
    guessField.disabled = true;
    guessSubmit.disabled = true;
    resetButton = document.createElement('button');
    resetButton.textContent = 'Start new game';
    document.body.append(resetButton);
    resetButton.addEventListener('click', resetGame);
  }

  function resetGame() {
    guessCount = 1;

    const resetParas = document.querySelectorAll('.resultParas p');
    for (let i = 0; i < resetParas.length; i  ) {
      resetParas[i].textContent = '';
    }

    resetButton.parentNode.removeChild(resetButton);

    guessField.disabled = false;
    guessSubmit.disabled = false;
    guessField.value = '';
    guessField.focus();

    lastResult.style.backgroundColor = 'white';

    randomNumber = Math.floor(Math.random() * 100)   1;
  }

  if (userGuess === randomNumber) {
    lastResult.textContent = "Congratulations! You got it right.";
    lastResult.style.backgroundColor = "green";
    lowOrHi.textContent = " ";
    setGameOver();
  } else if (guessCount === 10) {
    lastResult.textContent = "Game over! No more turns!";
    setGameOver();
  } else {
    lastResult.textContent = "Wrong";
    lastResult.style.backgroundColor = "red";
    if (userGuess < randomNumber) {
      lowOrHi.textContent = "Your last guess was too low!";
    } else if (userGuess > randomNumber) {
      lowOrHi.textContent = "Your last guess was too high!";
    }
  }

  guessCount  ;
  guessField.value = " ";
  guessField.focus();
}

guessSubmit.addEventListener("click", checkGuess); 
 <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">

<div class="container">
  <h1 id="main_header">Number guessing game</h1>

  <p>We have selected a random number between 1 and 100. See if you can guess it in 10 turns or fewer. We'll tell you if your guess was too high or too low.</p>

  <div class="form">
    <label for="guessField">Enter a guess: </label>
    <input type="text" id="guessField" class="guessField">
    <input type="submit" value="Submit guess" class="guessSubmit">
  </div>

  <div class="resultParas">
    <p class="guesses"></p>
    <p class="lastResult"></p>
    <p class="lowOrHi"></p>
  </div>
</div> 

введите описание изображения здесь

Мне бы очень хотелось, чтобы кнопка «Начать новую игру» находилась внутри div вместе с остальными элементами, чтобы я мог сделать ее более привлекательной.

Ответ №1:

Вы можете получить элемент, к которому вы хотели бы прикрепить кнопку, с помощью document.getElementsbyClassName функции, а затем добавить к нему:

В следующем примере я присоединил элемент к form классу div.

 let randomNumber = Math.floor(Math.random() * 100)   1;

const guesses = document.querySelector(".guesses");
const lastResult = document.querySelector(".lastResult");
const lowOrHi = document.querySelector(".lowOrHi");

const guessField = document.querySelector(".guessField");
const guessSubmit = document.querySelector(".guessSubmit");

let guessCount = 1;
let resetButton;
guessField.focus();

function checkGuess() {
  let userGuess = Number(guessField.value);
  if (guessCount === 1) {
    guesses.textContent = "Previous guesses: ";
  }
  guesses.textContent  = userGuess   " ";

  function setGameOver() {
    guessField.disabled = true;
    guessSubmit.disabled = true;
    resetButton = document.createElement('button');
    resetButton.textContent = 'Start new game';
    formElem = document.getElementsByClassName("form")[0]
    formElem.append(resetButton);
    resetButton.addEventListener('click', resetGame);
  }

  function resetGame() {
    guessCount = 1;

    const resetParas = document.querySelectorAll('.resultParas p');
    for (let i = 0; i < resetParas.length; i  ) {
      resetParas[i].textContent = '';
    }

    resetButton.parentNode.removeChild(resetButton);

    guessField.disabled = false;
    guessSubmit.disabled = false;
    guessField.value = '';
    guessField.focus();

    lastResult.style.backgroundColor = 'white';

    randomNumber = Math.floor(Math.random() * 100)   1;
  }

  if (userGuess === randomNumber) {
    lastResult.textContent = "Congratulations! You got it right.";
    lastResult.style.backgroundColor = "green";
    lowOrHi.textContent = " ";
    setGameOver();
  } else if (guessCount === 10) {
    lastResult.textContent = "Game over! No more turns!";
    setGameOver();
  } else {
    lastResult.textContent = "Wrong";
    lastResult.style.backgroundColor = "red";
    if (userGuess < randomNumber) {
      lowOrHi.textContent = "Your last guess was too low!";
    } else if (userGuess > randomNumber) {
      lowOrHi.textContent = "Your last guess was too high!";
    }
  }

  guessCount  ;
  guessField.value = " ";
  guessField.focus();
}

guessSubmit.addEventListener("click", checkGuess); 
 <!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">

  <title>Number guessing game</title>
  <link rel="stylesheet" href="style.css">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
  <style>
    @import url('https://fonts.googleapis.com/css2?family=Fira Sans:wght@300;400;500;700amp;display=swap');
  </style>
</head>

<body>
  <div class="container">
    <h1 id="main_header">Number guessing game</h1>

    <p>We have selected a random number between 1 and 100. See if you can guess it in 10 turns or fewer. We'll tell you if your guess was too high or too low.</p>

    <div class="form">
      <label for="guessField">Enter a guess: </label>
      <input type="text" id="guessField" class="guessField">
      <input type="submit" value="Submit guess" class="guessSubmit">
    </div>

    <div class="resultParas">
      <p class="guesses"></p>
      <p class="lastResult"></p>
      <p class="lowOrHi"></p>
    </div>
  </div>

  <script src="script.js" defer></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
</body>

</html> 

Ответ №2:

Просто найдите свой родительский div:

 const yourDiv = document.getElementById('yourDivId');
 

А затем добавить к нему кнопку:

 yourDiv.appendChild(resetButton);