JavaScript: Reversing the Sequence of XML Elements

I am looking to reverse the order of this list using JavaScript. I have tried different methods that I know, but the below code shows it in a straight manner. I am not familiar with XML nodes and how to completely reverse it.

<messages>
    <messageset>
        <name>torje</name>
        <time>1533904431</time>
        <message>Vvvhjhf</message>
    </messageset>
    <messageset>
        <name>moneyman</name>
        <time>1533904437</time>
        <message>njkjlmkmkl</message>
    </messageset>
    <messageset>
        <name>anjali</name>
        <time>1533904445</time>
        <message>A hi fyi bk MLS egg FG ch bhi CDG jk IC</message>
    </messageset>
</messages>

In the current code, it displays the table in the following order:

torje - Vvvhjhf, moneyman - njkjlmkmkl, anjali - A hi fyi bk MLS egg FG ch bhi CDG jk IC
. Instead, I want to reverse it so that Anjali's message is displayed first, then Moneyman, and finally Torje (apologies for any errors in the messages).

function fetch() {

        setTimeout( function() {
        loadDoc()
        fetch();
    }, 100);

}


function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      myFunction(this);
    }
  };
  xhttp.open("GET", "../clubs/club.xml", true);
  xhttp.send();
}
function myFunction(xml) {
  var i;
  var xmlDoc = xml.responseXML;
  var table="<tr><th>NAME</th><th>message</th></tr>";
  var x = xmlDoc.getElementsByTagName("messageset");
  for (i = 0; i < x.length; i++) { 
    table += "<tr><td>" +
    x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue +
    "</td><td>" +
    x[i].getElementsByTagName("message")[0].childNodes[0].nodeValue +
    "</td></tr>";
  }
  document.getElementById("demo").innerHTML = table;
}

Answer ā„–1

To organize the data, you can create an array and store each data row in it. Then utilize Array#reverse() on the array and convert it back to a string by using Array#join()

function myFunction(xml) {
  var rowsArray =[]
  var i;
  var xmlDoc = xml.responseXML;
  var table="<tr><th>NAME</th><th>message</th></tr>";
  var x = xmlDoc.getElementsByTagName("messageset");
  for (i = 0; i < x.length; i++) {
    // new variable `row`
    var row = "<tr><td>" +
    x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue +
    "</td><td>" +
    x[i].getElementsByTagName("message")[0].childNodes[0].nodeValue +
    "</td></tr>";
    // add row to array
    rowsArray.push(row)
  }
  // reverse the array and convert it to a string
  table += rowsArray.reverse().join('');
  document.getElementById("demo").innerHTML = table;
}

Answer ā„–2

At the moment, your for loop is handling the messages in a traditional order.

for (i = 0; i < x.length; i++) {

You have the option to simply reverse the flow of this loop:

for (i = x.length - 1; i >= 0; iā€”-) {

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Regain focus after selecting a date with Bootstrap datepicker

When initializing a bootstrap datepicker from eternicode with the parameter autoclose: true, there are two undesired behaviors that occur: After closing the picker, tabbing into the next field causes you to start at the beginning of the document again, w ...

What is the best way to retrieve a key from an Any type in Angular?

Currently, I am facing a challenge in extracting key values from an Any type while working with Angular/Typescript. For instance, if another segment of the program is providing this data: { Amy: { age: 7, grade: 2 }, Max: { ...

To clear the previous result of an AJAX call in JavaScript, reset the function or variable

I encountered a problem previously, and now another issue has come up. It appears that the previous result from my ajax JavaScript is still being displayed, and I need to prevent that from happening. I've tried deleting the variable, setting it to und ...

Creating a guideline for input to allow for both empty strings and a set number of characters

How can I set a rule for input to only allow two conditions: The input must be exactly 5 characters long. The input can also accept an empty string. Here is what I've done so far: new Vue({ el: '#app', data: () => ({ code: ...

Developing a custom React Native function for applying 'Title Case' to text

I've been trying to create a function that automatically converts input from users into Title Case. The code I have written seems correct to me, but it's not producing the desired output. It's failing to capitalize the first letter of each w ...

The userName data is not being displayed in the console.log when using socket.io

I'm currently in the process of developing a chat application using socket.io. My goal is to log the user's name when they join the chat. I have set up a prompt on the client side to capture the user's input and emit it to the server. Howeve ...

Why does JSON.parse need to be run twice - once for a string and once for an object?

When I send a JSON string via websocket (Socket.io) from a Node.js server to a client's browser, I find that I have to execute the JSON.parse function twice in order to extract an object from the received JSON string. This behavior is confusing to me. ...

When the page loads, the HTML side menu will automatically scroll to the active item in a vertical

My website features a vertical side menu with approximately 20 items. The issue I am facing is that when a user clicks on an item, the destination loads but the side menu must be manually scrolled to find the active item if it's located at the bottom ...

Jquery display function experiencing unresponsiveness

Currently, I am trying to implement some show/hide functionality in my JavaScript file: $(document).ready(function() { $('#me').hide(); $('#send').click(function() { $('#me').show("slow"); }); }); Strange ...

How to utilize local functions within a ko.computed expression

Why isn't this line of code working? I'm using durandal/knockout and my structure is like this define(function () { var vm = function() { compute: ko.computed(function() { return _compute(1); // encountering errors }); ...

The computed value failing to refresh

I'm facing an interesting issue. I am currently developing a simple time tracking application. Here is the form I have created: <form class="form" @submit.prevent="saveHours"> <div class="status"> <div class="selector" v-f ...

Retrieving & Refreshing Data with ajax and Jquery

I have been working on developing a forum system using jQuery, PHP, Bootstrap, and other technologies. The forum allows users to post, delete, and edit their posts. I have implemented an edit button for the author of the post, which triggers a modal wind ...

Accessing an XML document from a distant server

I'm attempting to parse an XML file from this website (which actually has several options depending on your needs): Here's what I attempted with the first one (unsuccessfully): <?php $xml = simplexml_load_file('http://apis.skplanetx.com ...

Executing server-side method with jQuery in .Net 1.1

Currently, I am utilizing .net1.1 and attempting to invoke a server-side method using jQuery upon clicking the browser's Close button. However, my code does not seem to be functioning correctly. I have provided my code below for reference. Can anyone ...

When a change occurs in the <input/> element within a <div>, the onChange event in React will be triggered

Upon entering text into the input, the onChange function is triggered on this code snippet. How is it possible for the onChange event to occur on a div element? Is there documentation available that explains this behavior? class App extends Component { ...

How do you modify the up vector of the camera in three.js?

When working with three.js, I encountered a situation where I set the camera's focal point using camera.lookAt(0, 0, 0), but the camera's up vector ended up pointing in a random direction. I have a specific up vector in mind that I want the camer ...

How to incorporate Base64 textures into Three.js

I am currently trying to load textures from URLs, but since my backend code is generating planets, I need to display them using Base64 instead. I'm experimenting with procedural generation, so I'd rather not save the image and then load it via U ...

An effective approach to positioning HTML elements at specific X and Y coordinates

I have an innovative project idea! The concept is to enable users to create points by clicking on the display. They can then connect these points by clicking again. However, I am facing a challenge when it comes to creating HTML elements at the exact loc ...

Invoke the ng-click function within the ng-change function

Just starting out with angularjs and I have a question. I am currently using single select and I want to retrieve the value selected and based on that value, perform an action. For example, if the value is "DELETE" then I would like to trigger the ng-clic ...

Develop a CakePHP CRUD view using a JavaScript framework

Creating a CRUD view in Cake PHP is simple with the following command: bin/cake bake all users This command builds the users table for CRUD operations. Is there a JavaScript framework that offers similar simplicity? ...