I am currently attempting to use jQuery to append multiple buttons to a bottom of a form. In an attempt to keep my code somewhat clean, I am using document.createElement() statements to add the items to the form, like so :
//Form-footer is a container of buttons on the end of the form.
$("#form-footer").append(
$(document.createElement('button'))
.prop({
class: "btn btn-success",
id: "save-button"
})
.html("Save")
)
.append(
$(document.createElement('button'))
.prop({
class: "btn btn-secondary",
id: "preview-button"
})
html("Preview Report")
)
However, I noticed a styling issue : My buttons end up squished together, without the margin in between them.
I was able to discover the cause of the styling issue. While the development console may show that the items are in new lines and indented properly....
...They actually lack both, as can be revealed by 'Edit as Html':
Manually editing this HTML to add new lines and indentation in Chrome's developer console fixes the styling issue, but that's obviously not helpful in production applications.
Why doesn't append add new lines for elements? What do I need to do to get appended tags to have proper new lines in their parents?
As I understand it, the $(document.createElement('div'))... is processed by the .append wrapper as a string, or at least, it behaves quite similarly for the purpose of this answer.
.append() essentially concatenate the contents of the parent tag and the input into one long string.
Therefore, a new line character is not inserted between the attached elements. To insert the newline and correct the styling, use .append('\n') before adding any buttons after the first.
Why after the first? Inspect the HTML of the question: the first button is already on a separate line.
$("#form-footer") .append( $(document.createElement('button')) .prop({ className: "btn btn-success ml-1", id: "save-button" }) .html("Save") ) .append('\n') //Append a new line .append( $(document.createElement('button')) .prop({ className: "btn btn-secondary", id: "preview-button" }) .html("Preview Report") )Change this:
class: "btn btn-success"
to this:
class: "btn btn-success ml-1"
and you should be good to go.
By default there is no margin on buttons in Bootstrap.