How to convert an HTML to text using Javascript

Asked

Viewed 88 times

-3

I’m having a little doubt if there’s any way to do this:

Code

function escrever() {
  var text = document.getElementById("text").value;
  var paragrafo = document.getElementById("modal-body").innerHTML;
  paragrafo = paragrafo + "<p>" + text + "</p>";

  document.getElementById("text").value = '';
  document.getElementById("modal-body").innerHTML = paragrafo;
}

function titulo() {
  var text = document.getElementById("title").value;
  var paragrafo = document.getElementById("modal-body").innerHTML;
  paragrafo = paragrafo + "<h1>" + text + "</h1>";

  document.getElementById("title").value = '';
  document.getElementById("modal-body").innerHTML = paragrafo;
}
<html>

<body>
  <div class="form">
    <div class="title">
      <textarea id="title" placeholder="Digite seu titulo"></textarea>
      <input type="button" value="Add" onclick="titulo()">
    </div>
    <div class="texto">
      <textarea id="text" placeholder="Digite seu paragrafo"></textarea>
      <input type="button" value="Add" onclick="escrever()">
    </div>
  </div>
  <div class="visualizar">
    <div class="visu-content">
      <div id="modal-body">
      </div>
    </div>
  </div>
  </main>

</body>

</html>

It would be like a blog (it’s just a school project).

I have textareas for writing and div with id="modal-body" for viewing how the post will look.

In the div <div id="modal-body"> would like to catch all children (HTML markup p, h1) and return something like text :

"<h1>Titulo</h1><p>Lorem</p>"

so that I can put it in the database as a text attribute, and finally put that text on another page using the innerHTML.

  • Why don’t you use your own innerHTML to do this then?

1 answer

-2

Use the innerHTML function to capture html.

let elemento = document.querySelector("#modal-body")
let html = elemento.innerHTML

From there, you will have the html content of the div in text format to save to the database, and if you put this html text inside another element, it will go as html.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.