Get values for the javascript-clicked div

Asked

Viewed 25 times

-3

How do I get the values corresponding to DIV clicked?`

Example of the first div if clicked, returns:

Aid = 1

aCodigo = 8477459164

aNome = Room

function vistoriaIniciar(object) {
  let aID     = object.document.getElementsByClassName('aID').value;
  let aCodigo = object.document.getElementsByClassName('aCodigo').value;
  let aNome   = object.document.getElementsByClassName('aNome').value;
	
  
  alert(aID +" - "+ aCodigo +" - "+ aNome);
}
<div id="divListaAmbientes" class="">


  <div class="lista fade" onclick="vistoriaIniciar(this)">
    <h1>Sala</h1>
    <input class="aID" type="hidden" value="1">
    <input class="aCodigo" type="hidden" value="8477459164">
    <input class="aNome" type="hidden" value="Sala">
  </div>
  

  <div class="lista fade" onclick="vistoriaIniciar(this)">
    <h1>Quarto</h1>
    <input class="aID" type="hidden" value="2">
    <input class="aCodigo" type="hidden" value="8477459164">
    <input class="aNome" type="hidden" value="Quarto">
  </div>


</div>

1 answer

4


When you define an attribute onclick in some HTML element and calls a function by passing the this as argument, you will receive the element instance.

So, how this instance you receive as a parameter implements the interface Element, you can invoke methods like getElementsByClassName, querySelector, among others.

So the problem is here:

object.document.getElementsByClassName('aID').value;

The element you are receiving does not have a property document. The document which you refer to is a global in the browsers, and cannot be accessed through another element.

Just do it this way:

object.getElementsByClassName('aID')[0].value;
//                                  ↑↑↑
//           Note que utilizamos o `[0]` aqui.

Note also that I added a [0] at the end of the call getElementsByClassName, since that method returns a HTMLCollecion, who does not have the method value. To do this, we need to get the first element returned (or some other one of your choice).

  • 1

    You were faster than me and worse than for that question there’s no other answer.

  • 1

    Luiz, thank you very much for your explanation!

Browser other questions tagged

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