dimanche 4 juillet 2021

is it efficient to traverse through the DOM to find elements I want or manipulate querySelector method to directly get them?

my question: is it efficient to traverse through the DOM to find elements I want to manipulate or should I just use querySelector or getElementById methods to directly get them?

in this example, it's a simple Guess game, and what I did is to select them directly through querySelector

(function ()
{
    let highscore = 0;
    let randomNumber = generateRandomNumber();
    const messageEl = document.querySelector('.message');
    const guessBtn = document.querySelector('.guess');
    const resetBtn = document.querySelector('.again');
    const scoreLabel = document.querySelector('score');
    const highscoreLabel = document.querySelector('highscore');

    function generateRandomNumber()
    {
        return Math.floor(Math.random() * 20 + 1);
    }
})();
  <body>
    <header>
      <h1>Guess My Number!</h1>
      <p class="between">(Between 1 and 20)</p>
      <button class="btn again">Again!</button>
      <div class="number">?</div>
    </header>
    <main>
      <section class="left">
        <input type="number" class="guess" />
        <button class="btn check">Check!</button>
      </section>
      <section class="right">
        <p class="message">Start guessing...</p>
        <p class="label-score">💯 Score: <span class="score">20</span></p>
        <p class="label-highscore">
          đŸ„‡ Highscore: <span class="highscore">0</span>
        </p>
      </section>
    </main>
    <script src="script.js"></script>
  </body>

I am asking about which solution is good if I have multiple DOM elements to select(NOT adjacent, each one is indifferent parent DIV).

What am really need to know, what is the best practice between these two approaches? and is it okay to have multiple elements selected by querySelector like my solution?




Aucun commentaire:

Enregistrer un commentaire