Reed Armstrong
Reed Armstrong

Reputation: 65

Looping over array of HTML elements and adding to Array

I'm new to Javascript and I'm trying to copy text from all span elements with the class "copyme", sort them in reverse order, and concatenate the strings together. Once I do this, I am trying to add a paragraph containing this information to the div tag with id="copyhere"

Here's what I have so far:

    var copy= document.getElementsByClassName("copyme").innerHTML;
    var arr = [];
    for (x = 0 ; x < copy ; x++){
       arr.push(x);
   }
    arr.concat().reverse();
    document.getElementById('copyhere').innerHTML = arr;

Nothing happens when I do this.

Any thoughts on how to proceed? Thank you.

Upvotes: 0

Views: 57

Answers (3)

kadhar
kadhar

Reputation: 1

This might help

  var copy= document.getElementsByClassName("copyme");
  var arr = [];
  for (var x = 0 ; x < copy.length ; x++) {
     arr.push(copy[x].innerHTML);
    }
  document.getElementById('copyhere').innerHTML = arr.reverse().toString();

Upvotes: 0

Oleksandr  Fedotov
Oleksandr Fedotov

Reputation: 384

var copy= document.getElementsByClassName("copyme");
    var arr = [];
console.log(copy)
    for (var i = 0 ; i < copy.length ; i++){
       arr.push(copy.item(i).innerHTML);
   }
    arr.concat().reverse();
    document.getElementById('copyhere').innerHTML = arr;
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div class="copyme">1</div>
  <div class="copyme">2</div>
  <div class="copyme">3</div>
  <div id="copyhere"></div>
</body>
</html>

Upvotes: 0

doubleOrt
doubleOrt

Reputation: 2507

Here you go:

 var copy = document.getElementsByClassName("copyme");
    var arr = [];
    for (x = 0 ; x < copy.length ; x++){
       arr.push(copy[x].innerHTML);
   }
   arr.reverse();
   document.getElementById('copyhere').innerHTML = arr.join("");

If you have any questions, feel free to ask :)

Upvotes: 1

Related Questions