I am rendering a similar construct to the below with some server side code. The server side code inserts hard returns in between the project label and text fields. Not a big deal except the below jQuery code inserts the project label and text fields mashed together.
var projectLabel = $('<label for="project">Project</label>');
var projectField = $('<input type="text" name="project" id="projectName" />');
projectLabel.insertBefore($(this));
projectField.insertBefore($(this));
Because of this discrepancy the elements rendered server side have a space between them while the ones rendered on the client do not. I’ve tried adding a at the end of each line to no avail. Unfortunately, I have been unable to remove the hard returns outputted by the server side code. Further because of the space I can’t fix this with CSS. What are my options for adding spacing via jQuery?
When the server side code creates this, with the whitespace between the
labelandinputtags, it is inserting text which is sent to the browser. The browser then interprets that text (as HTML) and builds a DOM tree.When you use
insertBefore()in jQuery on the client side, you are inserting DOM nodes directly into the tree.The difference is that the server-generated text ends up creating three sibling nodes: the label, a text node, then the input; while the client side is only creating two nodes: just the label and the input.
If you create a text node with a single space (it doesn’t even have to be a non-breaking space) and insert it between the other two nodes it should appear the same.
I can’t tell ya off the top of my head how to create a text node in jQuery.