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

1

I have in the HTML document a certain element that has ordinal numbers 0-9.

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

1- capturing the output of the element id , which is in a tag <span>
2- make the inversion of 9 - 0
3 - put it back in the element.

Attempt 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>
    
asked by anonymous 28.06.2016 / 00:34

1 answer

1

Some problems in your code:

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

b) The strings do not have the method reverse who has it are the Arrays. So you have to create and "describe" an array to reverse this text.

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

You can do everything like this:

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

jsFiddle: link

    
28.06.2016 / 00:45