dannysh
dannysh

Reputation: 19

Get my own attribute's data with jQuery

I use jQuery to build dynamically a . Because I need to catch later the double-click events on the table's cells, and I need to know exactly which row and column were (double) clicked, I set my own attribute on each of the rows and on each column, i.e.:

<tr data-tr-number="2">
    <td data-td-number="1">John</td>
    <td data-td-number="2">Due</td>
    <td data-td-number="3">U.S.A.</td>
</tr>

Now, when I try later to get the values of these attributes (and also the html value of the element), I get an error. What am I doing wrong?

Thnx

this.attr("data-td-number")   --->   Uncaught TypeError: undefined is not a function

same for:

this.html    or     this.closest("tr").attr("data-tr-number")

Upvotes: 1

Views: 694

Answers (2)

jayson.centeno
jayson.centeno

Reputation: 835

or you can just do this.

$(this).data("td-number")

Upvotes: 0

dfsq
dfsq

Reputation: 193301

The thing is that this points to the HTMLTableCellElement object, not jQuery instance object. So you can't use attr method on it. Instead use:

$(this).attr("data-td-number") 

You can verify it easily:

console.log(this instanceof HTMLTableCellElement); // true
console.log($(this) instanceof jQuery); // true

You can always wrap pure HTML element into jQuery function to construct new instance of the jQuery with all necessary methods like attr, closest, etc.

Upvotes: 1

Related Questions