search

Home  >  Q&A  >  body text

ReplaceAll() in JavaScript was not found in the HTML page </em>

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粉323224129P粉323224129279 days ago446

reply all(1)I'll reply

  • P粉926174288

    P粉9261742882024-03-31 12:56:14

    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

    reply
    0
  • Cancelreply