Reputation: 25
I want to have a click function for the entire <tr>
, but when I click on it, I want to return the child element of where my mouse clicked. I know I can just do a <td>
function, but is it possible to achieve this without specifying the child element with the function?
HTML
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<tr>
JS/Jquery
$(document).on("click", "tr", function () {
return child clicked element.text;
});
Upvotes: 0
Views: 1553
Reputation: 138
You can easily get parents and child nodes of the elements you clicked using dom traversal technique in javascript.
document.getElementById('tr').addEventListener('click',(e)=> console.log(e.target.childNodes) )
You can execute the code and check your console and work as you wish.
Upvotes: 1
Reputation: 27051
You can use something like e.target
where e
is the event:
$(document).on("click", "tr", function(e) {
console.log(e.target);
});
You can try console.log(e)
then you can see a lot of information for the element that you have clicked on.
Demo
$(document).on("click", "tr", function(e) {
console.log(e.target);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<tr>
</tbody>
</table>
Upvotes: 3