How to replace text in multiple divs according conditional?

I need to replace the text of many divs, where according to the text of each div, put a text or another.

Example: If the text is 0, replace it with "no quota" and if it is different from 0, put "Yes it has".

Html code:

 <div><p id="text">1</p></div>
 <div><p id="text">0</p></div>
 <div><p id="text">1</p></div>

JS code:

    $('#text').text(function(){
        if($(this).text() == '0')
        {
            $(this).text('No quota');
        }
        else
        {
            $(this).text('"Yes it has');
        }
    });

But only changes the first element and the others left with the same text. As I can change the text for each item? Greetings from Chile.

Answers 1

  • There are two problems.

    First, as others have noted, you should be using a class instead of ID if you want to match multiple elements.

    Second, when you give a function argument to .text(), it receives the old text as an argument, and should return the new text rather than calling .html() within it. So it should be:

    $('.text').text(function(i, oldtext) {
      return oldtext == '0' ? 'No quota' : 'Yes it has';
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div><p class="text">1</p></div>
    <div><p class="text">0</p></div>
    <div><p class="text">1</p></div>


Related Articles