Reputation: 25799
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.
Upvotes: 1
Views: 10855
Reputation: 3466
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.
Upvotes: -2
Reputation: 112000
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).
Upvotes: 5
Reputation: 171914
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 () { ... });
Upvotes: 0