Heisenberg
Heisenberg

Reputation: 5279

How to get DOM element in jQuery

I would like to get result that is clicked DOM element.

When I try below code, it return jQuery object.

my desired result is like this

<td>1</td> ← clicked DOM element

Are there any method to get this?

jQuery($ => {
  $('td').on('click', function() {
console.log($(this));
})
});
td {
padding:5px;
border:solid black 1px;}

table{
border-collapse:collapse;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</table>

Upvotes: 0

Views: 49

Answers (4)

Karmdip joshi
Karmdip joshi

Reputation: 160

Just change console.log($(this)) to console.log(this) in your click event.

Because JQuery using only this not wrapped $(this).

Upvotes: 0

Manjuboyz
Manjuboyz

Reputation: 7066

You can try something like this:

$(document).ready(function() {
  $('td').on('click', function() { /* your click event */
    console.log("you clicked", this);
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
  </tr>
</table>

Upvotes: 1

Scott Marcus
Scott Marcus

Reputation: 65808

Just don't wrap this in JQuery.

jQuery($ => {
  $('td').on('click', function() {
console.log(this);
})
});
td {
padding:5px;
border:solid black 1px;}

table{
border-collapse:collapse;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</table>

Upvotes: 1

JohnSnow
JohnSnow

Reputation: 454

Just change $(this) to this

jQuery($ => {
  $('td').on('click', function() {
console.log(this);
})
});
td {
padding:5px;
border:solid black 1px;}

table{
border-collapse:collapse;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</table>

Upvotes: 1

Related Questions