How can I remove 'white space text nodes' from my HTML?

18,634

Solution 1

I second Rory McCrossan's suggestion. Since span is inline element the spaces between them are preserved in html output. And newlines are changed to spaces too. For Example:

<div>
 <span>A</span> <span>B</span>
</div>

<div>
 <span>A</span>
 <span>B</span>
</div>

<div>
 <span>A</span><span>B</span>
</div>

Solution 2

HTML adds "white space text node" after some elements ( all inline elements), because it considers the white space between these elements part of them and it preserves them. So you can remove white space in html source or with javascript: from the inspector see which element has nextSibling empty text node. In your case it's span, and do this for each element:

element.nextSibling.parentNode.removeChild(element.nextSibling);
Share:
18,634

Related videos on Youtube

Atul Kumar
Author by

Atul Kumar

Updated on June 04, 2022

Comments

  • Atul Kumar
    Atul Kumar almost 2 years

    I am getting an unwanted line before my <span> elements, and it shows as an empty dot in the developer mode of Firefox. How do I get rid of it?

    It is not pseudo element of the div, so span::before doesn't work. And I have no idea how it is generating.

    <div class="coll-details">
        <h5>Div title</h5>
        <span class="fa counts fa-eye">&nbsp;234</span>
        <span class="fa counts fa-heart">&nbsp;123</span>
        <span class="fa counts fa-comment">&nbsp;123</span>
        <span class="fa counts fa-share">&nbsp;123</span>
    </div>
    

    The white space text nodes are being adding before the span tags.

    Find the image here

    • Atul Kumar
      Atul Kumar
      @RoryMcCrossan did that.. but it is not because of the spaces or special characters i guess. I have no idea how this empty bit is generating.
  • lubosdz
    lubosdz over 4 years
    This is quite annoying behaviour of FF. All other browsers (inlc. IE11) ignore spaces inside HTML source and render it properly. Only Firefix (tested Quantum 66.04) adds extra pixels between them. Should be reported as a bug actually. Removing white space solves the issue, but source becomes hardly legible - which a often need to inspect during development.
  • Mamrezo
    Mamrezo over 2 years
    Nop, Google Chrome behave like FF by today