ZeroByte
ZeroByte

Reputation: 321

Change text in multiple html elements with same class in jquery

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 ?

Upvotes: 0

Views: 5984

Answers (2)

Solaiman Hossain
Solaiman Hossain

Reputation: 167

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>

Upvotes: 0

charlietfl
charlietfl

Reputation: 171669

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'
});

Upvotes: 4

Related Questions