Kyle Kyle - 1 month ago 4
Javascript Question

Find replace html using javascript

I've read a bunch of different posts and I can't figure out why this isn't working for me. Any help would be greatly appreciated. I'm sure it's something simple.

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>

<script type="text/javascript">

$("body").children().each(function() {
$(this).html($(this).html().replace(/®/g,"<sup>®</sup>"));
});

</script>

</head>

<body>

<div>HelloWorld®</div>

</body>
</html>

Answer

you must wait after page ready so add your function inside $(document).ready(function(){....}) or move your <script>...</script> tag as last element inside <body>...</body>

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


</head>

<body>

    <div>HelloWorld®</div>
    <script type="text/javascript">

    $("body").children().each(function() {
        $(this).html($(this).html().replace(/®/g,"<sup>®</sup>"));
    });

    </script>
</body>
</html>

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script type="text/javascript">

   $(document).ready(function(){
 $("body").children().each(function() {
        $(this).html($(this).html().replace(/®/g,"<sup>®</sup>"));
    });

});
    </script>

</head>

<body>

    <div>HelloWorld®</div>

</body>
</html>