0

I need to get a substring from each div element and display the substring as first 5 letters in the text.

I used jquery given below, but this code gives result as andy is displayed in all the output. but I want display result relevant , regarding substrings in the blocks.

$('.lblName').text($('.lblName').text().substr(0, 5))
code:<div class="name">andy oned be</div>
<div class="name">sumothad </div>
<div class="name">glimps hist</div><div class="name">sample name</div>

output andy sumot glimp sampl

my wrong output is andy andy andy andy

0

2 Answers 2

3

You should use each to iterate over all the .lblNames:

$('.lblName').each(function() {
    var newText = ($(this).text()).substr(0, 5);
    $(this).text(newText);       
});

Demo: https://jsfiddle.net/tusharj/56g0vqpf/

Sign up to request clarification or add additional context in comments.

2 Comments

how we use substr(0, 5)) in jquery
@saty FYI, this isn't relevant to jQuery but javascript ;)
0

You can use:

$('.lblName').text(function () {
    return $(this).text().substr(0, 5);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.