querySelector takes class? (JAVASCRIPT)


  • QA Engineer

    I did a function to change a photo when an element is added in my table, table that I created a class to manage to change the photo, but to get the element of the html, I need to use the querySelector, but I am not getting it with class, but when it is with id it goes.

    Ex:

    function teste() {
      var elemento = document.querySelector('info-status');
    
    var conteudo = elemento.textContent || elemento.innerText;
    
    var teste = conteudo.length;
    
    if (teste > 0) {
    
      var img = document.getElementById('TrocaPost');
      var imgg = document.getElementById('TrocaEntregue');
      var image = document.getElementById('TrocaViagem');
      img.src = 'caminhao/caminhaoCERTOazul.png';
      imgg.src = 'caminhao/caminhaoCERTOazul.png';
      image.src = 'caminhao/caminhaoCERTOazul.png';
    
    }
    

    }

    the info-status when it is id, it takes, but when it is class it does not catch.
    Is there something wrong with my code or the querySelector just grabs ID?



  • Good afternoon!

    O querySelector can capture any element of the DOM. Imagine the selector syntax is close to the CSS.

    Here is a practical example below:

    HTML:

    var divElement = document.getElementById('div');
    var buttonElementId = document.querySelector('button#buttonSquareID');
    var buttonElementClass = document.querySelector('button.buttonSquareClass');
    

    // por ID utliliza-se o "#"
    buttonElementId.onclick = function () {
    let newSquareElement = document.createElement('div');
    newSquareElement.textContent = 'Utilizando ID';
    divElement.appendChild(newSquareElement);
    }

    // por Class utliliza-se o "."
    buttonElementClass.onclick = function () {
    let newSquareElement = document.createElement('div');
    newSquareElement.textContent = 'Utilizando Class';
    divElement.appendChild(newSquareElement);
    }

    <!DOCTYPE html>
    <html>

    <head>
    <title>SQUARE</title>
    </head>

    <body>
    <div id="div">
    <button id="buttonSquareID"> Create text using ID </button>
    <button class="buttonSquareClass"> Create text using Class </button>
    </div>
    </body>

    </html>

    I hope you helped. Hugs




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2