Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append a space after an element

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");
like image 566
Sameh Farahat Avatar asked Dec 19 '11 14:12

Sameh Farahat


People also ask

How do you add extra space in HTML?

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   .

How do you append a space in JavaScript?

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!

How do you leave a space in HTML?

To add non-breaking space or real space to your text in html, you can use the   character entity.


2 Answers

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.

like image 146
Filip Roséen - refp Avatar answered Oct 24 '22 13:10

Filip Roséen - refp


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
like image 14
pimvdb Avatar answered Oct 24 '22 13:10

pimvdb