Reputation: 3580
I have a table and I want to add a new row to this table. I load html of the row from the server. Returned html has some other commented out html on the top. Because of that comment adding row doesn't work properly. jQuery removes <tr>
and <td>
tags and adds plain text from <td>
elements. Is it a bug or expected behaviour?
<table id="tbl">
<tr><td>old1</td></tr>
<!-- <abc -->
<tr><td>old2</td></tr>
</table>
<input id="add" type="button" value="add"/>
JavaScript:
$("#add").click(function() {
$("#tbl tr:last").after("<!-- <abc --><tr><td>New</td></tr>");
});
P.S. The issue is because of '<' in the comment. It works ok with normal comments. And it would also work with '<' if the comment was inserted into/from div elements rather than table/tr. What would be your suggestion to fix this issue without removing comment from the html on server-side.
Upvotes: 0
Views: 156
Reputation: 1
if you get always string like that and you don't want to have comment at all, you can strip it off
$("#add").click(function() {
var responseString = "<!-- <abc --><tr><td>New</td></tr>";
var index = responseString.indexOf("-->")+3;
var formatedString = responseString.slice(index);
$("#tbl tr:last").after(formatedString);
});
Upvotes: 0
Reputation: 18682
You can simply remove comments by using regular expressions. Code(Demo on JSFiddle):
$("#add").click(function() {
var rawHTML = "<!-- <abc --><tr><td>New</td></tr>";
var HTMLToAdd = rawHTML.replace(/<!--[\s\S]*?-->/g, '');
$("#tbl tr:last").after(HTMLToAdd);
});
Shorter version:
$("#add").click(function() {
$("#tbl tr:last").after("<!-- <abc --><tr><td>New</td></tr>".replace(/<!--[\s\S]*?-->/g, ''));
});
Upvotes: 1
Reputation: 2519
Referring to my comment above - e.g. the below JS works...
$("#add").click(function() {
newRow = '<!-- <abc --><tr><td>New</td></tr>';
var newRow = newRow.replace('<!-- <', '<!-- ');
$("#tbl tr:last").after(newRow);
});
where the newRow is actually the data returned by your server call.
Upvotes: 1