woodbine woodbine - 2 months ago 8
Javascript Question

truncating text, ignoring child nodes javascript

I'm trying to truncate a string within a div that also contains a span tag, but my script is gathering up the span tag converting it to text and pushing it back, how do I ignore the child data in a tag.

HTML:

<div class="oo-roboto-override row-title">
<span class="hidden-lg-up" itemprop="name">
Title:
</span>
This is the text that I want to truncate
</div>


Javascript:

$(".row-title").each( function() {
var g = (this).innerHTML;
var x = ". . . ";
var leng = 50;
var html = g.substring(0, leng)+"";
var allHTML = html+x;
$(this).text(allHTML);
});

Answer

Just iterate text nodes:

$(".row-title").each(function() {
  var leng = 25;
  [].forEach.call(this.childNodes, function(child) {
    if(child.nodeType === 3) { // text node
      var txt = child.textContent.trim();
      if(txt.length > leng) {
        child.textContent = txt.substr(0, leng) + "…";
      }
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="oo-roboto-override row-title">
  <span class="hidden-lg-up" itemprop="name">
    Title: 
  </span>
  This is the text that I want to truncate
</div>

Comments