I have HTML that looks like this:
<table>
<tbody>
<tr><td><button> Split </button></td></tr>
<tr><td><button> Split </button></td></tr>
<tr><td><button> Split </button></td></tr>
<tr><td><button> Split </button></td></tr>
<tr><td><button> Split </button></td></tr>
<tr><td><button> Split </button></td></tr>
</tbody>
</table>
My program should do the following when any one of the buttons are clicked:
- Split the ‘tbody’ node into two ‘tbody’ nodes. For instance, if you pressed the second button, the first two rows will be the children of one ‘tbody’ node and the other rows will be the children of another ‘tbody’ node.
- Create a new ‘tbody’ node right in between those two ‘tbody’ nodes.
- The innerHTML of the new ‘tbody’ node should be
<tr><td><p> Clicked </p></td></tr>
So if you click the second button, the desired html would be
<table>
<tbody>
<tr><td><button> Split </button></td></tr>
<tr><td><button> Split </button></td></tr>
</tbody>
<tbody>
<tr><td><p> Clicked </p></td></tr>
</tbody>
<tbody>
<tr><td><button> Split </button></td></tr>
<tr><td><button> Split </button></td></tr>
<tr><td><button> Split </button></td></tr>
<tr><td><button> Split </button></td></tr>
</tbody>
</table>
However, my javascript program fails to do this.
This is my javascript code.
$("button").on("click", function() {
var currentRow = $(this).parent().parent();
var htmlStr = "</tbody>";
htmlStr += "<tbody>";
htmlStr += "<tr><td><p>Clicked</p></td></tr>";
htmlStr += "</tbody>";
htmlStr += "<tbody>";
currentRow.after(htmlStr);
console.log($("table").html());
});
You can go to this JsFiddle link to test out my code and see what it ends up doing. Also, the last line of my code doesn’t print out html neatly. If you know how to make it print it in a better way, please let me know.
2
Answers
I think, you are targeting the wrong tag, you get the parent tr instead of getting the tbody parent.
Tell me if this is what you expect ?
You cannot manipulate HTML with partial HTML strings. Any start tag will be completed automatically when you append it
This was not trivial but works as expected