How to remove the "whitespace-only text node" from the DOM that appears in the HTML

2

It seems that HTML by default puts damn " whitespace-only text node " between inline elements with this I get a "margin" between elements that I can not remove from DOM

I know there are solutions like putting display:flex in the parent, or putting float in the elements. But I wanted to remove all these whitespace node at once without needing these artifacts (or gambiarras as margin-left:-4px ).

FireFox shows DevTools these nodes

Hereisanothersimpleexamplesimulatingtheproblem:

ul li {
    display: inline-block;
    padding: 10px;
    background-color: palevioletred;
}
<h2>Exemplo com Imagem</h2>
<div>
    <img src="http://unsplash.it/100/100"alt="">
    <img src="http://unsplash.it/100/100"alt="">
    <img src="http://unsplash.it/100/100"alt="">
    <img src="http://unsplash.it/100/100"alt="">
</div>
<br>
<img src="http://unsplash.it/100/100"alt=""><img src="http://unsplash.it/100/100"alt=""><img src="http://unsplash.it/100/100"alt=""><img src="http://unsplash.it/100/100"alt="">
<br>
<h2>Exemplo com ul/li { display:inline-block }</h2>
<ul>
    <li>item|</li>
    <li>item|</li>
    <li>item|</li>
    <li>item|</li>
</ul>
<br>
<ul>
    <li>item|</li><li>item|</li><li>item|</li><li>item|</li>
</ul>

When Chrome renders the code, it places each LI in a line, even in code being on one line! Note that even Chrome placing each LI in one row is still buggy and the other is not ...

Doesanyonehaveanytipsonhowtoremovethiswhitespace-onlytextnodebetweenelementsoftheDOM,evenwithjQueryorsomethinglike

LinktoMozilla'sarticleonthesubject: link

Another interesting article: link

    
asked by anonymous 28.03.2018 / 15:31

3 answers

3

You can remove by deleting nodeType 3 , which represent nodes of text (including spaces), but this will also remove text if any.

For this you can use .contents().filter() :

$('#teste').contents().filter(function(){
    return this.nodeType == 3;
}).remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="teste">
    <img src="http://unsplash.it/100/100"alt="">
    <img src="http://unsplash.it/100/100"alt="">
    <img src="http://unsplash.it/100/100"alt="">
    <img src="http://unsplash.it/100/100"alt="">
</div>
    
28.03.2018 / 15:50
4

The line break will generate a whitespace in HTML in inline-block elements, but commenting will solve

<div>
 <img src="" alt=""><!--
--><img src="" alt="">
</div>
    
06.04.2018 / 18:33
2

Another way to eliminate spaces is to set font-size: 0 , but you will have to reset the font size on those elements if there are any text in child elements .

Example:

#teste{
   font-size: 0;
}
<div id="teste">
    <img src="http://unsplash.it/100/100"alt="">
    <img src="http://unsplash.it/100/100"alt="">
    <img src="http://unsplash.it/100/100"alt="">
    <img src="http://unsplash.it/100/100"alt="">
</div>
    
29.03.2018 / 08:44