querySelector takes class? (JAVASCRIPT)

Asked

Viewed 749 times

0

I made a function to change a photo when an element is added in my table, table that I created a class to be able to change the photo, but to get the html element, I need to use querySelector, but I’m not getting with class, but when it is with id it will.

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’s id, it takes, but when it’s class it doesn’t take. Is there something wrong with my code or querySelector only takes ID?

1 answer

4

Good afternoon!

The querySelector can capture any DOM element. Imagine that the selector syntax is very close to CSS.

Follow 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 it helped. Hugs

  • 1

    It would be worth noting that this method returns only the first element that fits the criterion

  • Very good observation Lauro!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.