Sentimo
Sentimo

Reputation: 29

How to crop text without removing the div element, jquery

<div class="ins"> test test test <div class="temp">123</div></div>

The script deletes the div with class "temp"

$('.ins').text(function(){
return $(this).text().slice(0,5);});   

Upvotes: 1

Views: 331

Answers (5)

SilverSurfer
SilverSurfer

Reputation: 4368

You can easy achieve this with a simply span inside the div:

$('.ins > span').text($('.ins > span').text().slice(0,5))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ins"><span> test test test </span><div class="temp">123</div></div>

Upvotes: 1

Hanif
Hanif

Reputation: 3797

Please try this piece of code, also keep it mind that this code will work only your given DOM structure:

$('.ins').html(function(){
    return $(this).text().slice(0,5) + '<div class="temp">'+ $(this).find('.temp').text() +'</div>';
});

Upvotes: 1

Sinisa
Sinisa

Reputation: 82

Changing @void's code you can use

$(function(){
  $(".ins .temp").html("");
})

to remove the text from temp class and leave the div empty

Upvotes: 1

Murat Seker
Murat Seker

Reputation: 916

Get the value inside .temp div and clear the content from the same div element. In here div's content assinged to a variable.

var res = $('.ins .temp').html();
 $('.ins .temp').html("");
$('#t').html(res);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ins"> test test test <div class="temp">123</div></div>
<h2 id="t"></h2>

Upvotes: 2

void
void

Reputation: 36703

Instead of removing, just hide the div.

$(function(){
  $(".ins .temp").hide();
})

Upvotes: 1

Related Questions