Jquery - trim inner HTML?

13,865

Solution 1

var $mydiv = $('#mydiv');
$mydiv.html($.trim($mydiv.html());

This should take the contents any element, trim the whitespace from it and reset it as the content.

Solution 2

I don't really know why you want to do this but it seems like you are using jquery, so you can use the trim helper:

var $stuff = $(...the messy html you have above including the outer div);
var tidy = $.trim( $stuff.html() );
// tidy has no more div wrapper so you can do this:
return "<div>" + tidy "</div>"
// or this (but i dunno that it won't pad it again)
$stuff.html(tidy)
Share:
13,865
Tim
Author by

Tim

Updated on June 17, 2022

Comments

  • Tim
    Tim almost 2 years

    I somehow need to trim() the innerHTML of my content... so I have something like this:

    <div>
         <b>test</b>
    
    123 lol
              </div>
    

    I basically want to rid of the white space that is ONLY between <div> and the next character, and the white space just before the closing </div>.

    So the outcome would be:

    <div><b>test</b>
    
    123 lol</div>