Saryk
Saryk

Reputation: 355

Access text of an HTML element in an EventListener function

I have a table of about two dozen cells, each containing some text. I'd like to copy the text of a cell when it is clicked.
My <td> elements don't have IDs.

I have this js code that allows me to put an onClick() event to all of them, and they do prompt the "Hello" message :

var x = document.getElementsByTagName("td");
for (var i = 0; i < x.length; i++) {
    x[i].addEventListener("click", function() {
        alert("hello");
    });
}

How do I access the text elements from within the EventListener's function ?

Upvotes: 0

Views: 58

Answers (3)

Vaibhav Chauhan
Vaibhav Chauhan

Reputation: 360

If you are using jquery you can do it this way: table1 is class name of table

$(".table1 td").on("click", function(){
        var thisCell = $(this).html();
            alert(thisCell);
    });

Upvotes: 0

Mamun
Mamun

Reputation: 68923

You can refer the currently clicked td with this keyword. Then simply access innerText or textContent property on that like this.textContent:

x[i].addEventListener("click", function() {
    alert(this.textContent);
});

Demo:

var x = document.getElementsByTagName("td");
for (var i = 0; i < x.length; i++) {
    x[i].addEventListener("click", function() {
        alert(this.textContent);
    });
}
table, th, td {
  border: 1px solid black;
}
<table style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th> 
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
  <tr>
    <td>John</td>
    <td>Doe</td>
    <td>80</td>
  </tr>
</table>

Upvotes: 2

Maheer Ali
Maheer Ali

Reputation: 36584

You can use Event.target and get its innerText.

Event.target: is the element on which the event is occurred.

var x = document.getElementsByTagName("td");
for (var i = 0; i < x.length; i++) {
    x[i].addEventListener("click", function(e) {
        alert(e.target.innerText);
    });
}

Upvotes: 2

Related Questions