get the text of an element (td) with javascript

0

I have a question how to obtain the value of an element (the text within it) since apparently I do not achieve it with .value, .innerHTML, textContent and now I thought I would do it with target..but I do not solve it..someone could you help me ... thanks and thanks

document.getElementById("mano1").addEventListener("click",saludar);
document.getElementById("mano2").addEventListener("click",saludar);

      function saludar(e){
        alert("haz pulzado el tr"+ e.target.??);
      }
<table>
    <tr id="mano1">hola mundo1</tr>
    <tr id="mano2">hola mundo2</tr>
</table>
    
asked by Juandev 13.12.2018 в 07:39
source

1 answer

4

Several things:

  • HTML: You must create your HTML well. Notice that you have the <head> without closing, you have not created the <table> tag to contain your <tr> and also, you are missing the <td> within the <tr>
  • Inside your JS you have this that is incorrect: .?? (in fact in your example it gives an error)
  • The saludar function has a e parameter that you are not passing in the addEventListener
  • Said call to the function saludar you have to pass it by reference in a function(){} if you do not want it to be invoked immediately. What you want is to pass that reference to the function and only invoke it when they click.
  • To get the value contained in your <td> you can use innerText .
  • I leave an example working.

    document.getElementById("mano1").addEventListener("click",function(){saludar(this)});
    document.getElementById("mano2").addEventListener("click",function(){saludar(this)});
    
    function saludar(e){      
      console.log("Has pulsado el tr: "+ e.innerText);
    }
    <html>
    <head>
    </head>
    <body id="body">
    <table>
        <tr id="mano1"><td>Hola mundo 1</td></tr>
        <tr id="mano2"><td>Hola mundo 2</td></tr>
    </table>
    </body>
    </html>

    And here another one using bind

    let el1 = document.getElementById("mano1");
    el1.addEventListener("click",saludar.bind(null,el1));
    let el2 = document.getElementById("mano2");
    el2.addEventListener("click",saludar.bind(null,el2));
    
    function saludar(e){   
      console.log("Has pulsado el tr: "+ e.innerText);
    }
    <html>
    <head>
    </head>
    <body id="body">
    <table>
        <tr id="mano1"><td>Hola mundo 1</td></tr>
        <tr id="mano2"><td>Hola mundo 2</td></tr>
    </table>
    </body>
    </html>
        
    answered by 13.12.2018 / 08:46
    source