Why does adding TR markup with a space or a queue before it cause it to go outside the body?
I ran into curious behavior when adding inline markup <tr>
to a table via JQuery. Every time I added a line that I was generating as a string, it was placed outside mine tbody
. Then I found out about it.
It works great if I add it like this:
$("table").append("<tr><td>Test</td></tr>");
But if I add a space or a line break before <tr>
it adds a line outside tbody
.
$("table").append(" <tr><td>Test</td></tr>");
$("table").append("\n<tr><td>Test</td></tr>");
It's funny that if I use any other character it still works fine. Is there a specific reason for this behavior?
//Works fine without anything before the tr
$("table").append("<tr><td>Second row</td></tr>");
//Works fine also with any character
$("table").append("sdfa<tr><td>Third row</td></tr>");
//Doesn't work when there an whitespace or newline
$("table").append(" <tr><td>Fourth row</td></tr>");
$("table").append("\n<tr><td>Fifth row</td></tr>");
table tbody td {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td>First row</td>
</tr>
</table>
source to share
In the jQuery utility,, manipulationTarget
there is a helper utility that determines target
to add a row. In particular:
function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ?
elem.getElementsByTagName("tbody")[0] ||
elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
elem;
}
What happens when you pass a string with whitespace
at the beginning, it creates a document chunk where the first child is a text
node, not tr
. Timesheet text ( sdfa
) is removed in another utility.
source to share
This behavior is consistent with the jQuery documentation
.append (content [, content])
Content type: htmlString or Element or Array or jQuery DOM element , array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.
Where htmlString is identified as HTML if it starts with<tag ... >
source to share