0

Through this question I found out here that there are downsides in extending DOM objects. Is it OK to do something like the following?

var tr = $('<tr>');
tr.myCustomProperty = 'Some string value';

I know that there is a .data() method on jQuery, but the above seems easier to work with. I also wonder if my tr variable is holding an actual tr DOM Element or any other kind of object.

Community
  • 1
  • 1
DiegoAlfonso
  • 237
  • 5
  • 15
  • 3
    No, they are jquery objects. the moment you re-select the tr or use a method that generates a new jquery object, the property is lost. – Kevin B Nov 15 '13 at 18:13
  • No, essentially $('') is a function whose name is "$" and parameter is ''. It's not a DOM object – aarryy Nov 15 '13 at 18:15

2 Answers2

3

Kevin is incorrect. You can store something in the TR in most browsers by doing the following:

var tr = $('tr').eq(0); // get a single TR from the DOM
var actualElement = tr[0]; // get the actual element object from the jQuery object
actualElement.myCustomProperty = 'Some string value';
Anthony Iacono
  • 203
  • 1
  • 9
  • 4
    Kevin's statement is correct. Diego added the property to the jQuery object. That is - as Kevin wrote - a bad idea. – Tobias Nov 15 '13 at 18:19
2

jQuery handles DOM objects in special array called jQuery object. You can think of it as array of DOM elements which is extended to have all the jQuery methods.

You can access the DOM element in your example like this:

tr[0]

but all the reasons not to store data that way still apply.

As @Kevin B mentioned, it's not ok to do what you're trying to do (extending jQuery object) because you'll lose the custom properties on every reinitialization.

mechanicalfish
  • 12,696
  • 3
  • 46
  • 41