iSimpleDesign
iSimpleDesign

Reputation: 403

Limiting string text within div

Can someone tell me if their is a way to limit text within div classes.

example

<div class="mon">December</div>
<div class="mon">November</div>
<div class="mon">October</div>

$('.mon').hide().text();

var month = $('.mon').text().substr(0,3);

$('.mon').append(month).show();
alert(month);

trying to output

Dec Nov Oct

Any help?

Upvotes: 2

Views: 4489

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074148

You can do this:

$('div.mon').text(function() {
    return $(this).text().substring(0, 3);
});

Live example

text, like a lot of other "setter" functions of jQuery (html, attr, etc.), accepts a function it will call to get the value to set for each element.

Upvotes: 2

Nick Craver
Nick Craver

Reputation: 630379

.text() can take a function, like this:

$('.mon').text(function(i, t) { return t.substr(0, 3); });

You can test it out here.

Upvotes: 3

Related Questions