user3653087 user3653087 - 6 months ago 34
Javascript Question

JQuery: Cut off div text after 4 characters

I only want to display the first four characters of a div, but it seems to be more difficult than needed and google isn't very helpful. Different variations of this don't seem to work:

$("#div").html(this.html().substring(0,4));


I really want to avoid having an extra variable in there that stores the text first.

Answer

Use a callback for the .html(),

$("#div").html(function(){
    return $(this).html().substring(0,4);
});

Demo

$(this).html() and not this.html()

You can also use .text() in this case if the div consists only of plain text.

$("#div").text(function(){
    return $(this).text().substring(0,4);
});

Refer :

Slice vs Substring

Turns out substring is relatively faster.

JsPerf test : slice() vs substring() vs others