dannysh dannysh - 4 years ago 58
jQuery Question

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")

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download