1

I have paragraph that has a read more link nested in it.

<p>Lorem ipsum blah blah blah <a href="link">Read More</a></p>

I need to truncate the paragraph text and end it with an ellipsis without affecting anything in the <a></a> tag.

I can do the truncation of the text using $(p).text($(p).text().substring(0,n)+'...'); but of course if I grab the paragraph using $(p).text() it would include the link and would lop it off.

Is there a way to grab, and then replace with the truncated version, the text of the <p> without affecting the </a>. Preferably without having to use any regex or having to clone the link and re-append it?

DasBeasto
  • 2,082
  • 5
  • 25
  • 65

3 Answers3

2

You can do something like this using nodeType. Then you can change value using textContent property.

For a text node, the nodeType property will return 3.

alert($('p').contents().filter(function() {
  return this.nodeType == 3;
})[0].textContent);

//set new value
$('p').contents().filter(function() {
  return this.nodeType == 3;
})[0].textContent = 'New text ';
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<p>Lorem ipsum blah blah blah <a href="link">Read More</a></p>
rrk
  • 15,677
  • 4
  • 29
  • 45
1

$(function() {
  
  var x = $("p").contents().get(0).nodeValue; // This will grab the text ignoring the other nodes:

  $("p").html(x.substring(0, 5) + '...' + $("p").find("a").wrap("<p>").parent().html()); // Setting x and appending the <a> html

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>Lorem ipsum blah blah blah <a href="link">Read More</a>
</p>
void
  • 36,090
  • 8
  • 62
  • 107
0

you can try following script:

 $(document).ready(function () {
        var hrefTag = $('a').attr('href');   
        $('p').html('<a href="' + hrefTag + '">Read More</a>');
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Lorem ipsum blah blah blah <a href="link">Read More</a></p>
Sunil Kumar
  • 3,142
  • 1
  • 19
  • 33