Which correct way to use Reverse(); in a given element id

Asked

Viewed 23 times

1

I have in Document HTML a certain element that has ordinal numbers from 0 to 9.

I’m trying to use the method reverse(); to reverse the order of numbers in my element. The logic should be:

1- capture the output (out) of the element id, that is in a tag <span>
2- do the inversion of 9 - 0
3- re-insert into the widget.

Trial Code

<script>
window.onclick = function(){
    var listar = document.getElementById('txt');
    document.getElementById('txt').innerHTML   = listar.reverse();
}
</script>

<body>
    // Aqui No corpo do documento HTML
    <span id='txt'>0 1 2 3 4 5 6 7 8 9</span>
</body>

1 answer

1


Some problems in your code:

a) When you use listar.reverse(); this listing is an element, and I imagine you need the .innerHTML of the element.

b) Strings do not have the method reverse the ones who have it are the Arrays. So you have to create and "decrypt" an array to invert this text.

c) Your <script> is not even in the body nor in the head. Maybe I was like that for example, but it must be inside one of them.

You can do anything like this:

window.onclick = function() {
  var listar = document.getElementById('txt');
  listar.innerHTML = listar.innerHTML.split('').reverse().join('');
}

jsFiddle: https://jsfiddle.net/kr0v10ax/

Browser other questions tagged

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