Ways to flip the sequence of lines within a div without altering the formatting, word arrangement, and other elements

I need to rearrange the order of my lines while preserving the styling of words and the sequence I have created.

Code Snippet:

<textarea id="mytext"">
    Buy - 3 Potatoes $6.25
    Sold - 3 Napkins $7.12
    Buy - 5  Fries $11.62
    Sold - 7 Potatoes $14.32
</textarea>

<div id = "myresult"></div>

Although I have structured the words correctly with appropriate styles, now I need to reverse the ordering of the lines. I am using notepad++ and still in the early stages of learning JavaScript.

JavaScript:

var mytext = document.getElementById('mytext');
var result = document.getElementById('myresult');
var lines = mytext.value.split('<br>');
result.innerHTML = '';
for(let i = 0;i < lines.length;i++){
    var line = lines[i];
    var list = [];
    list.unshift(line);
    list.unshift("<br>");
    var word = line.split(' ');
    var n1 = line.match(/[0-9]+/g);
    var n2 = line.match(/[0-9]+\.[0-9]+/g);
    var check = line.match(/Buy/);
    var check2 = line.match(/Sold/);
    if(check) {  
        result.innerHTML += "<span style='color:green;'>" + word[0] + "</span>" + ' ' +  word[2] + ' ' + word[3] + ' total:$' + (n1[0]*[n2]).toFixed(2) + "<br>";
    }
    else if(check2) {  
        result.innerHTML += "<span style='color:blue;'>" + word[0] + "</span>" + ' ' +  word[2] + ' ' + word[3] + ' total: $' + (n1[0]*[n2]).toFixed(2) + "<br>";
    }
    else { 
        result.innerHTMl + " ";
    }

}

Even though I have set up the colors and fixed the display order, the last step is to reverse the lines and show them through innerHTML.

The original plan was to use an array[], and then within every loop iteration, try to unshift the line along with
but it resulted in errors like a bunch of commas or random words being displayed without any colors.

The desired outcome should resemble what is generated after running the code snippet. The updated innerHTML should be visible inside the div container.

<div id="result">
    <span style='color:blue;'>Sold</span> 7 Potatoes total: $100.24<br>
    <span style='color:green;'>Buy</span> 5 Fries total: $58.1<br>
    <span style='color:blue;'>Sold</span> 3 Napkins total: $21.36<br>
    <span style='color:green;'>Buy</span> 3 Potatoes total: $18.75<br>
</div>

Answer №1

Building on my earlier point, consider incorporating the JavaScript method reverse() as a preliminary step when generating new elements.

For example:

var lines = mytext.value.split("\n").reverse();

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

The Navbar-Burger in Bulma is not linking to menu items properly in Vue.js 2

I have been working on implementing a navbar for my application using Vue 2.0 and Bulma. Everything seems to be working fine on desktop screens, but on smaller screens, the burger icon appears without any elements displayed. It's just there. <temp ...

Using the PUT method in Node.js to set the ID

Need help with setting ID value from frontend apiRoutes.put('/intake', function(req, res) { Intake.findById({id, function(err, intake) { if (err) res.send(err); check : true; intake.save(function(err) { ...

Achieving a shadow effect above a CSS border: tips and tricks

<div class="row"> some content <div class="info-box"> some other content </div> </div> .row { float: left; margin-bottom: 1.5%; border: 1px solid #e3e3e3; -webkit-border-radius: 4px; -moz-border ...

Is there a way to ensure the alignment of items remains consistent, especially for the rightmost column, by enclosing them within a div element?

I'm currently working with Vue.js and using a UI component framework designed for it. I'm facing an issue where aligning numbers like 500 or 5000, as well as icons, is proving to be difficult. The numbers in the rightmost column need to be aligne ...

Header with absolute positioning doesn't play nice when nudged in Chrome

Take a look at the HTML page on this JSFiddle link: http://jsfiddle.net/rb8rs70w/2/ The page features a "sticky" header created using CSS with the property position: absolute. ... <body class="body-menu-push"> <header role="banner"> ...

Button displayed on complete Bootstrap 4.5 Card

When running the code below, the text "Click Me" appears when the mouse hovers over it. I actually want "Click Me" to be displayed for the entire card (list). <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel= ...

The DOM lacks the assigned 'id' in the HTML

While working in the Moodle platform (version 3.5.7) using the Atto editor in both Chrome and Firefox, I have been attempting to assign an ID to a specific row class called "span9". My main goal is to give this element a unique ID and then reference it wit ...

Having trouble running the command "npm start"?

Today I started working with electron and followed a tutorial to create a basic browser window application. However, when I ran the command 'npm start' in the terminal, I encountered multiple errors. Below is the console error message along with ...

Having difficulties achieving successful API requests in Next.js and Snipcart

I'm currently diving into the world of Snipcart, and I'm encountering some issues connecting to your API. I'm using Next.js and haven't been able to find any solutions on the forum or in the documentation that address my specific proble ...

dispatch a WebSocket message within a route using Express.js

The Objective: Imagine a bustling marketplace with multiple shops. I'm working on a dedicated page localhost:3000/livePurchases/:storeId for shop owners to receive real-time notifications whenever they make a new sale. https://i.stack.imgur.com/VdNz ...

Integrate blogger into my website with automatic height adjustment and scrolling functionality

Check out my website here. I've integrated a blogger component into it. Can anyone provide guidance on creating parallel scroll and automatically resizing sections based on the blog's height? Thanks, M ...

Refresh the Parse.com User through a Stripe Webhook

Despite finding many Parse / Stripe questions on this platform, none have been able to assist me with my specific issue. In my mobile application, I have both free and paid features. A variable stored on the User class in Parse.com is used to check permis ...

Obtain the following image with every click

I have a div with images inside. I created two arrows (previous, next) within a larger div using the src of one of the images as the background URL for each arrow. My goal is to make the next arrow change the large image to the src of the following image w ...

Multiple Button Triggered jQuery Ajax Function

I'm currently working on a project where I retrieve data from MySQL to create 4 buttons. I am using jQuery/ajax to trigger an event when any of the buttons are clicked. However, only the first button seems to be functioning properly, while the other t ...

What is the best way to develop a widget that loads asynchronously by implementing AJAX, JavaScript, and PHP?

Currently, this widget is in need of items that are sourced from a php file. For instance, the javascript function should generate a table within this div element. <div id="widget"></> The aim is to dynamically update the content with the ht ...

Comparing Jquery ajax object in Internet Explorer is not possible

Currently, I am utilizing jQuery's ajax function to fetch an HTML page. Upon success, a data object is retrieved. I aim to compare this data object to a string to determine the necessary actions. This functionality performs as expected in Firefox and ...

The JavaScript code is receiving an "undefined" response from the WebService method, despite expecting a valid return value

One of my WebService's methods is designed to return a boolean: [WebMethod(EnableSession = true), ScriptMethod(UseHttpGet = true)] public bool StartMonitoring() { return Schedule.StartMonitoring(); } The method within the Schedule class looks li ...

Managing the height of a hero section with TailwindCSS and React.js

Embarking on my first website project using React and Tailwind has been an exciting learning experience. My vision is to showcase a Hero Section prominently at the top, with a Nav bar situated elegantly at the bottom of the screen. To bring this concept ...

There appears to be a glitch preventing Phonegap from properly syncing with Google Analytics

I'm currently developing an app using PhoneGap and I wanted to integrate Google Analytics into it. After installing this plugin via the CLI, I inserted the following lines of code within my deviceReady event: analytics.startTrackerWithId('UA-*** ...

What is the method for viewing a PDF file on ng-click without automatically downloading it in AngularJS?

When the user clicks on the link that says "Click to get your file", I am able to download the file. However, now I want to open the PDF file in a modal window and prevent the user from downloading it. This is My Controller: var resumeJson = { "j ...