Search code examples
javascriptsplitclassname

Replace a character in different elements with the same class in JavaScript?


I have several paragraphs in my page. They all have the same class name. I want to replace a character that is in all of them. I tried something like this:

  var str = $(".foo").html;
  var res = str.split(" ").join("");
  $(".foo").html = res;

But I get the error: TypeError: str.split is not a function

I noticed that if I target a single paragraph, with its unique Id, everything works fine. I just cannot do it with several paragraphs at the same time, using their class names.


Solution

  • $(".foo") returns a list, therefore, you should iterate over each paragraph and change its content. You can use the each function as follows:

    $( ".foo" ).each(function( index, element ) {
         $(element).html( $(element).html().split(" ").join("") );
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <p class="foo">hello world</p>
    <p class="foo">hello world</p>
    <p class="foo">hello world</p>