0

I've got links in one wrapper which have specific class. I know that i can change text with .text() in jQuery, but what if i have 2 or more texts in same class. How can I change them all at once ?

4
  • 1
    Where is the script? Commented Mar 6, 2016 at 17:55
  • use class selector in jquery to change all Commented Mar 6, 2016 at 18:00
  • @RajaprabhuAravindasamy that's not correct $('.someClass').text('new text') will change all. You are thinking about text() as getter but in fact that' will actually return all text in collection concatenated together . It's a weird one compared to all other getters Commented Mar 6, 2016 at 18:28
  • @charlietfl Yes, that is right. Just misunderstood. Commented Mar 6, 2016 at 18:31

2 Answers 2

4

Change all to same new string.

$('.someClass').text('new text');

Loop over all in class and modify existing text for each element

$('.someClass').text(function(_, oldText){
    return oldText + ' new text'
});
Sign up to request clarification or add additional context in comments.

Comments

0

Hope, this will help to change multiple HTML elements with same class with jquery

$(function () {
    $(".change-title").on("click", function (e) {
        $('.change-text').text($(this).data("desc"));
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<div class="change-text">
   Change Text 1
</div>

<p class="change-text">Change Text 1</p>
<a href="#" class="change-title" data-desc=" Change Text 1">button1</a>

<a href="#"  class="change-title" data-desc=" Change Text 2">button 2</a>

1 Comment

can you convert the jquery to use es6/vanilla JS?

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.