If you want to create a space between elements, you can achieve this by inserting a textNode
between them.
When adding a String
to HTML, the string is parsed as HTML which may result in the combination of multiple whitespaces into a single whitespace, generating a textNode
by the HTML parser. However, when using createElement
, textNodes need to be created manually by the user. Think of it as taking control and responsibility for generating HTML yourself.
var parent = document.getElementById('parent');
var htmlString = document.createElement('div');
htmlString.className= 'inline-block';
var textNode = document.createTextNode(' ');
var htmlString2 = document.createElement('div');
htmlString2.className= 'inline-block';
parent.appendChild(htmlString);
parent.appendChild(textNode);
parent.appendChild(htmlString2);
.inline-block {
display: inline-block;
width: 100px;
height: 20px;
border: 1px solid red;
}
<div id="parent"></div>
\n
can also be used for the same purpose, if you were attempting to add a line break.
var parent = document.getElementById('parent');
var htmlString = document.createElement('div');
htmlString.className= 'inline-block';
var textNode = document.createTextNode('\n');
var htmlString2 = document.createElement('div');
htmlString2.className= 'inline-block';
parent.appendChild(htmlString);
parent.appendChild(textNode);
parent.appendChild(htmlString2);
.inline-block {
display: inline-block;
width: 100px;
height: 20px;
border: 1px solid red;
}
<div id="parent"></div>