I was wondering how can I append a space after an element in JavaScript? I am creating an image and a span in for loop, and I want to append a space after the image and after the span. Here is how I create the tags:
var image = document.createElement("img");
Type where you want to insert an extra space. Add one non-breaking space character for every space you want to add. Unlike pressing the spacebar multiple times in your HTML code, typing more than once creates as many spaces as there are instances of .
Use the padEnd() and padStart() methods to add spaces to the end or beginning of a string, e.g. str. padEnd(6, ' '); . The methods take the maximum length of the new string and the fill string and return the padded string. Copied!
To add non-breaking space or real space to your text in html, you can use the character entity.
var host = document.createElement ("div");
host.appendChild (document.createElement ("img"));
host.appendChild (document.createTextNode (" "));
host.appendChild (document.createElement ("span"));
console.log (host.innerHTML);
output
<img /> <span></span>
You can achieve the same visual appearance by using the CSS property margin
on either the img
or span
.
Since you asked for some visual whitespace - the simplest and most flexible way is applying it through CSS, not using a space character:
img {
margin-right: 5px;
}
If you want to only apply it to the specific element you create, you can use JavaScript to apply the CSS: http://jsfiddle.net/aRcPE/.
image.style.marginRight = "5px"; // "foo-bar" becomes "fooBar" since
// the hyphen is not allowed in this notation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With