ReplaceAll() in JavaScript was not found in the HTML page </em>
P粉323224129
P粉323224129 2024-03-30 15:06:51
0
1
311

I'm not familiar with JavaScript and html. But I'm trying to implement a function using JavaScript.

I want to replace all <em> and </em> in the html page. So I inserted a piece of javascript code into the page:

function rep() 
{
    document.body.innerHTML
        = document.body.innerHTML
        .replaceAll("<em>", "_");
    document.body.innerHTML
        = document.body.innerHTML
        .replaceAll("</em>", "_");

}
window.onload=rep()
<!DOCTYPE html>
<html lang="en">
<!-- ... -->
<article>
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1 post-container">

                <p>(Weierstrass) 设 $z_{0}$ 是 $f$ 的本性奇点,那么对任意 $A \in \mathbb{C}<em>{\infty}$, 必存在趋于 $z</em>{0}$ 的点列 $\left{z_{n}\right}$, 使得 $\lim <em>{n \rightarrow \infty} f\left(z</em>{n}\right)=A$.</p>

            </div>
        </div>
    </div>
<!-- ... -->

</html>

Successfully replaced <em> with "_", but all </em> remained unchanged. Is there anything wrong with the code? Thanks!

P粉323224129
P粉323224129

reply all(1)
P粉926174288

Let's see what happens when the browser sees invalid html, for example:

test

console.log(document.body.innerHTML)
test

Print above test (and script)

This is because the browser removes invalid structures during parsing

When you do this

document.body.innerHTML
  = document.body.innerHTML
  .replaceAll("", "_");

You replaced all <em> tags correctly, but the closing tag was removed

On the other hand, this will also work:

document.body.innerHTML = document.body.innerHTML
  .replaceAll("", "_")
  .replaceAll("", "_");
test
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!