Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery replace hangs chrome

Why does this script freeze up Chrome? Also, is there a better way to do what I'm trying to do (replace all instances of a word with another word)?

<html>
  <body>      
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
      <script>
    $(document).ready(function(){   
    var replaced = $("body").html().replace('Foo','Bar');
    $("body").html(replaced);
    });
      </script>
      <p>Foo</p>
    </body>
</html> 
like image 685
Elliot Gorokhovsky Avatar asked Dec 06 '25 14:12

Elliot Gorokhovsky


1 Answers

Because the script that does the replacement is in the body. When you call .html(HTMLString) and HTMLString contains a <script>, jQuery executes the script. So after you replace the body, you're calling the code that replaces the body again, and when it runs it calls itself again, and so on.

You're also loading another copy of jQuery every time you do the replacement, because <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> is in the body.

One solution would be to put all the scripts in the <head> instead of the body. Another would be if you targetted just a container DIV that contains the real content of the page.

<html>
  <body>      
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
      <script>
    $(document).ready(function(){   
        var replaced = $("#content").html().replace(/Foo/g,'Bar');
        $("#content").html(replaced);
    });
      </script>
      <div id="content">
        <p>Foo</p>
      </div>
    </body>
</html> 

Also, when you give a string as the first argument to .replace(), it only replaces the first match. If you want to replace all matches, you need to use a regular expression with the g modifier.

like image 85
Barmar Avatar answered Dec 08 '25 18:12

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!