String pick up sentence text

Asked

Viewed 30 times

-3

I have a phrase the following random phrase: Pineapple, pear, apple and wanted in the variable var str = pick up my random phrase

<div class="page-header"><h1>Abacaxi, pera, maçã</h1></div>

<button onclick="myFunction()">botão</button>

<p id="demo"></p>

<script>
function myFunction() {
  var str = "";
  var res = str.split(" ");
  var palavras = str.split(' ');
  var reordenado2 = [palavras.pop()].join(' ');
  document.getElementById("demo").innerHTML = reordenado2;
}
</script>

1 answer

0


You can do it in several ways, one for example is the querySelector, following example:

<div class="page-header"><h1>Abacaxi, pera, maçã</h1></div>

<button onclick="myFunction()">botão</button>

<p id="demo"></p>

<script>
function myFunction() {
  var str = document.querySelector('div.page-header h1').innerText;
  var palavras = str.split(' ');
  var reordenado2 = palavras.reverse().join(' ');
  document.getElementById("demo").innerHTML = reordenado2;
}
</script>

Note: I made some changes at the end, because the way it was, (calling the pop) it only took the last element, as its variable is marked with a reordered name I put it as reverse just to make sense in the example.

Browser other questions tagged

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