Jump to content

replacing text on page, but breaks if i use body selector


toolman

Recommended Posts

Hi,

 

I have the following code which will replace text on my page. It works if the word is in a <p> tag, but if I change it to select the <body> or a <div>, the page completely breaks and displays a load of code on the page.

 

$("p").text(function () {
    return $(this).text().replace("foo", "bar");
});

 

 

Any ideas how I can search the whole body and replace text?

 

Thanks!

This seems to work

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
    $().ready(function() {
        $("#btnReplace").click(function() {
            var txt = $("body").html();
            var re = /foo/gi;
            txt = txt.replace(re,"bar");
            $("body").html(txt);
        })
    })
</script>
</head>
<body>
<h1>Foo Heading</h1>
<p>This is foo</p>
<table border="1">
  <tr><td>foo</td><td>123</td></tr>
  <tr><td>foobar</td><td>321</td></tr>
</table>
<input type="button" name="btnReplace" id="btnReplace" value="Replace">
</body>
</html>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.