views:

810

answers:

3

I have a jQuery wrapped element which I would like to append to a html row. I can't wrap my head around this, since append() seemingly accepts strings but not existing jQuery elements (I might be mistaken here). I have a following setup:

var row='<tr><td>data1</td><td>data2</td><td>';
var img=$('<img src="path/to/img.png"');
img.click(myClickHandler);

Now what I'm trying to do is to append this img element to my row and 'close' the row with a closing tag. I'm doing it as follows:

var jRow=$(row);
jRow.append(img);
jRow.append('</td></tr>');

After my row is ready I append it to my table:

$('#tableId').append(jRow);

Well, all above doesn't work, because I get [Object Object] instead of image tag in my added row.

My goal is to have a row with an image in last cell and a working click handler.

Pleease, help.

A: 

How about trying with jRow.html(), like this?

$('#tableId').append(jRow.html());

It should return you the actual HTML contents instead of the jQuery-wrapped element (jQuery object), which is probably what causes the problem, since append() expects to get a String to append.

miek
That html() call will only return what's contained within the <tr> - it won't return the actual <tr> itself. Also, this won't solve the main problem.
J-P
html() and append() or almost exactly the same in functionality; have a look at the jQuery source. And append() can accept strings, DOM elements, jQuery objects, pretty much anything...
J-P
Okay, thanks for the clarification! Glad you got it solved.
miek
A: 

I am not 100% sure, but I think HTML fragments should always be "complete", meaning that adding just "</td></tr>" will not work.

A solution would be to build a string with a complete HTML fragment, and then append it, instead of appending the pieces one at a time. You can always add the click handler after you created your jQuery object, like this:

jRow.find("img").click(function () { ... });
Philippe Leybaert
I would guess he already has a table he's just manipulating rows in. But besides that, I absolutely agree :)
miek
+2  A: 

When you pass a string to append() it is first "converted" to a DOM element/collection. So, every single string you pass to append() must be valid HTML/XHTML; you can't add bits of string on later. The image can still be appended to the table row even if you close the tags beforehand. E.g.

var row='<tr><td>data1</td><td>data2</td><td></td></tr>';
var img=$('<img src="path/to/img.png"/>');
img.click(myClickHandler);

var jRow = $(row);
$('td:last', jRow).append(img);


When you pass anything to append() or html() or prepend() (or any other similar method) try to forget about strings; what you just passed is no longer a string; it has been parsed as HTML and has been added to the document as a DOM element (or a number of DOM elements).

J-P
J-P, it worked like a charm, thank you!
Valentin Vasiliev