I have a simple HTML page that looks like this html page and this is the HTML code for it
<!DOCTYPE html>
<html>
<body>
<h1>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Tincidunt a gravida non, tincidunt condimentum nullam.
Aliquam mi augue, venenatis sed dolor eget. Aliquam venenatis felis, nullam ante est, nullam mattis massa nec nunc imperdiet convallis.</h1>
</body>
</html>
What I would like to do, is highlight every occurrence of the words "dolor" and "nullam" on the page. In order to achieve this, I have embedded the following JQuery instructions inside the HTML code, like so
<!DOCTYPE html>
<html>
<body>
<h1>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Tincidunt a gravida non, tincidunt condimentum nullam.
Aliquam mi augue, venenatis sed dolor eget. Aliquam venenatis felis, nullam ante est, nullam mattis massa nec nunc imperdiet convallis.</h1>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$("body").html($("body").html().replace(/dolor/gi, "<mark>dolor</mark>"));
$("body").html($("body").html().replace(/nullam/gi, "<mark>nullam</mark>"));
</script>
</body>
</html>
However, what I find is that only the first JQuery line gets executed, that is, only the word "dolor" is highlighted, and this is what I see on the page highlighted html page. What I expect to see instead, is something like this expected html page, where all occurrences of both words are highlighted. Any idea why the second JQuery line gets ignored and how I can fix it to achieve my expected result? Thank you all.
Each line of that script rewrites the entire content of the <body> element.
This includes the <script> element that is doing the rewriting.
This breaks the script.
Either:
<head> and wrap it in a DOM ready event handler.<main> element).