Jquery - ¿recortar HTML interno?

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> y el siguiente personaje, and the white space just before the closing </div>.

So the outcome would be:

<div><b>test</b>

123 lol</div>

preguntado el 31 de enero de 12 a las 08:01

Why? That's a sort of odd thing to need. -

@jjj $.trim is no a good option for manipulating the DOM. -

3 Respuestas

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.

Respondido el 31 de enero de 12 a las 12:01

You may be able to drill into the DOM and find whitespace text nodes and remove them more manually. But jQuery won't help there, and I have no idea how to do that. - Alex Wayne

not that hard - look at element.childNodes, A partir de .firstChild comprobar .nodeType == 3, remove the node if the .textContent property is all white space - repeat until first non text node is found. Then perform backwards from the last child node. - Alnitak

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)

Respondido el 31 de enero de 12 a las 12:01

Two good answers, I've chosen the slightly more concise. Many thanks! - Tim

actually neither of them are good answers - the correct approach would be to explicitly remove empty text nodes found at the start or end of the div's child list. But I don't have time to write that just now. - Alnitak

You can easily write a jQuery plugin to do this. I created both a static and instance method for this.

Puedes alternar el __DEBUG__TRIM_TYPE variable below to change the technique. Each case will produce the exact same result. They are different ways of achieving the same result.

// jQuery Plugin
// =============================================================================
(function($) {
  $.fn.trimHtml = function() {
    return this.html(function(index, html) {
      return $.trim(html);
    });
  };
  $.trimHtml = function(selector) {
    return $(selector || '*').filter(function() {
      return $(this).data('trim') === true;
    }).trimHtml();
  }
}(jQuery));

// Example
// =============================================================================
$(function() {
  var __DEBUG__TRIM_TYPE = 1; // You can change this to values between 1-3.
  
  switch (__DEBUG__TRIM_TYPE) {
      // Option #1. Select elements by a selector.
      case 1:
        $('.pre-block[data-trim="true"]').trimHtml();
        break;

      // Option #2. Filter elements by a selector and their data.
      case 2:
        $('.pre-block').filter(function() { return $(this).data('trim'); }).trimHtml();
        break;

      // Option #3. Apply function to all elements where the "trim" data is TRUE.
      case 3:
        $.trimHtml();
        break;
  }
});
h1 { font-size: 1.5em; }
.pre-block { display: inline-block; white-space: pre; border: thin solid black; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js"></script>

<h1>Not Trimmed</h1>
<div class="pre-block" data-trim="false">
  Text not to be trimmed.
  
</div>

<h1>Already Trimmed</h1>
<div class="pre-block" data-trim="false">Text already trimmed.</div>

<h1>Trimmed</h1>
<div class="pre-block" data-trim="true">
  Text that was trimmed.
  
</div>

respondido 09 mar '16, 20:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.