Creating a sort button in HTML that can efficiently sort various divs within a table is a useful tool for enhancing user experience

My HTML table is populated with various <td> elements. How can I arrange these divs based on IMDb rating, TomatoMeter, etc... [ CSS code is not provided below ]

<table>
  <tr class="row">
    <td class="column">
      <br>
      <div>
        <div>1<br></div>
        <div>
          <mark class="names">INTERSTELLAR</mark><br>
          <span><mark class="names">CHRISTOPHER NOLAN,2014</mark></span><br>
          <span><mark>US | Sci-Fi/Adventure</mark></span>
        </div>
        <br><br>
        <div class="rating">
          <p>
            <a href="" target="_blank"><img title="IMDB Rating" alt="IMDB" src="" class="imdb-img"></a>
            <a href=""><img title="Rotten Meter" alt="Rotten Tomatoes" src="" class="imdb-img"></a>
            <a href=""><img title="MetaScore" alt="MetaCritic" src="" class="imdb-img"></a>
            <img title="Audience Rating" alt="Google Rating" src="" class="imdb-img">
            <br>
            <span class="imdb-rate">8.6</span>&nbsp;&nbsp;<span class="imdb-rate">72%</span>&nbsp;&nbsp;
            <span class="imdb-rate">74%</span>&nbsp;&nbsp;<span class="imdb-rate">92%</span>&nbsp;&nbsp;
          </p>
        </div>
      </div>
    </td>

    <td class="column">
      <br>
      <div>
        <div>2<br></div>
        <div>
          <mark class="names">INTERN</mark><br>
          <span><mark class="names">CHRISTOPHER NOLAN,2014</mark></span><br>
          <span><mark>US | Sci-Fi/Adventure</mark></span>
        </div>
        <br><br>
        <div class="rating">
          <p>
            <a href="" target="_blank"><img title="IMDB Rating" alt="IMDB" src="" class="imdb-img"></a>
            <a href=""><img title="Rotten Meter" alt="Rotten Tomatoes" src="" class="imdb-img"></a>
            <a href=""><img title="MetaScore" alt="MetaCritic" src="" class="imdb-img"></a>
            <img title="Audience Rating" alt="Google Rating" src="" class="imdb-img">
            <br>
            <span class="imdb-rate">5.6</span>&nbsp;&nbsp;<span class="imdb-rate">70%</span>&nbsp;&nbsp;
            <span class="imdb-rate">54%</span>&nbsp;&nbsp;<span class="imdb-rate">91%</span>&nbsp;&nbsp;
          </p>
        </div>
      </div>
    </td>
  </tr>
</table>

TLDR; Numerous cells have varying IMDB, TomatoMeter... values. How do I organize (descending order) these cells based on these values?

Answer №1

To achieve this, you will need the following JavaScript:

  1. A method for selecting all elements of a specific type or class - querySelectorAll
  2. A way to sort an array based on a value or function - array.sort

In essence, you should gather all rows in the table, iterate through each column within the row while keeping track of their ratings, and then sort based on the desired rating.

Refer to the comments in the provided code for further clarification.

// Specify the rating you want to use for sorting (0=IMDB, 1=Rotten Tomatoes, etc.)
let rating = 0;

// Get a collection of all rows in the table
const rows = document.querySelectorAll('row');
let rowno, columnno; // Variables to track current row and column numbers

// Iterate over each row
for (rowno=0; rowno < rows.length; rowno++) {
  let row = rows[rowno];
  
// Array to store columns and their ratings
  let list = [];
  
// Get all columns (td elements) for this row 
  let columns = row.querySelectorAll('td');
  
// Iterate over all columns
  for (columnno = 0; columnno < columns.length; columnno++) {
    let column = columns[columnno];
    let ratings = column.querySelectorAll('.imdb-rate'); // Retrieve the four ratings for this column
// Store the column (td element) and its ratings
    list.push({'column': column, 'ratings': ratings});
    }
  
// Now we have all the ratings for each column in this row
// Sort the array by rating in descending order
  list.sort(function (a, b) {
    if (a.ratings[rating].innerHTML.replace('%', '') < b.ratings[rating].innerHTML.replace('%', '')) return 1;
    if (a.ratings[rating].innerHTML.replace('%', '') > b.ratings[rating].innerHTML.replace('%', '')) return -1;
    return 0;
  });

// Rewrite the contents of the current row
  for (columnno = 0; columnno < list.length; columnno++) {
    row.append(list[columnno].column);
  }
}
<table>
  <tr class="row">
    <td class="column">
      <br>
      <div>
        <div>1<br></div>
        <div>
          <mark class="names">INTERSTELLAR</mark><br>
          <span><mark class="names">CHRISTOPHER NOLAN,2014</mark></span><br>
          <span><mark>US | Sci-Fi/Adventure</mark></span>
        </div>
        <br><br>
        <div class="rating">
          <p>
            <a href="" target="_blank"><img title="IMDB Rating" alt="IMDB" src="" class="imdb-img"></a>
            <a href=""><img title="Rotten Meter" alt="Rotten Tomatoes" src="" class="imdb-img"></a>
            <a href=""><img title="MetaScore" alt="MetaCritic" src="" class="imdb-img"></a>
            <img title="Audience Rating" alt="Google Rating" src="" class="imdb-img">
            <br>
            <span class="imdb-rate">8.6</span>&nbsp;&nbsp;<span class="imdb-rate">72%</span>&nbsp;&nbsp;
            <span class="imdb-rate">74%</span>&nbsp;&nbsp;<span class="imdb-rate">92%</span>&nbsp;&nbsp;
          </p>
        </div>
      </div>
    </td>

    <td class="column">
      <br>
      <div>
        <div>2<br></div>
        <div>
          <mark class="names">INTERN</mark><br>
          <span><mark class="names">CHRISTOPHER NOLAN,2014</mark></span><br>
          <span><mark>US | Sci-Fi/Adventure</mark></span>
        </div>
        <br><br>
        <div class="rating">
          <p>
            <a href="" target="_blank"><img title="IMDB Rating" alt="IMDB" src="" class="imdb-img"></a>
            <a href=""><img title="Rotten Meter" alt="Rotten Tomatoes" src="" class="imdb-img"></a>
            <a href=""><img title="MetaScore" alt="MetaCritic" src="" class="imdb-img"></a>
            <img title="Audience Rating" alt="Google Rating" src="" class="imdb-img">
            <br>
            <span class="imdb-rate">5.6</span>&nbsp;&nbsp;<span class="imdb-rate">70%</span>&nbsp;&nbsp;
            <span class="imdb-rate">54%</span>&nbsp;&nbsp;<span class="imdb-rate">91%</span>&nbsp;&nbsp;
          </p>
        </div>
      </div>
    </td>
  </tr>
</table>

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

Issue with retrieving body class in Internet Explorer on Magento platform. The body class is not being recognized in IE, but works fine in Mozilla and Chrome

<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php echo $this->getLang() ?>" lang="<?php echo $this->getLang() ?>" dir="ltr"> <?php echo $this->getChildHtml('head') ?> <bod ...

Having difficulty with the javascript click() function in an html document

Thank you in advance for checking this out. In my web application, users can choose options from four separate drop-down menus. Once a selection is made, the software triggers a click() function that generates a new span element within a div: var activeF ...

Building secure applications with React and Express using private routes

In my experience, I have primarily utilized server-side rendering solutions to transfer data from the server to the client and display it in the browser. One of the key advantages of this approach is the ability to access data and send it to the client wi ...

Easiest and quickest method to retrieve metadata from a website

Currently, I am using preg_match to extract the 'title' from websites, however, it is loading very slowly. Here is what I have so far: This code sends links to a function: <?php foreach($savedLinks as $s) { echo "<div class='sa ...

Counting the days: how to calculate without using negative numbers

After performing the calculation, the result shows -30. Is there a way to eliminate the negative sign and get 30 instead? $days = (strtotime(date("Y-m-d")) - strtotime($info['expiredate'])) / (60 * 60 * 24) echo abs($days); Any suggestions on ...

Guide to inputting text into the Dev element

I am encountering a challenge with automating gist creation on GitHub. The issue arises when trying to input text into the gist content-box (see attached image). Despite attempting to use Javascript executer, I have not been successful. JavascriptExecutor ...

Utilize a function in module.exports that calls for a variable within the module

I am currently working on designing my modules in such a way that they don't need to be required multiple times. In my approach, I am passing arguments from the main app.js file to all of my modules. One of the modules I have is for user login and it ...

Filter JSON data deeply for specific values

I am attempting to filter JSON data based on user checkbox selections in JavaScript. The challenge I'm facing is implementing multi-level filtering. The data has two dimensions that need to be filtered: first by OS selection and then by a selected que ...

When using Jquery, the search button consistently retrieves the same data upon the initial click event

How can I ensure that my Ajax call retrieves data from the remote database based on the updated search criteria every time I click the search button? Currently, the system retrieves results based on the initial search criteria even after I modify it and cl ...

Leverage Firebase cloud functions to transmit a POST request to a server that is not affiliated with

Is it feasible to utilize a firebase cloud function for sending a post request to a non-Google server? It appears that being on the blaze plan is necessary in order to communicate with non-google servers. Essentially, I aim to perform a POST action to an ...

Transforming React drag and drop page builder state into a functional html, css, and js layout

Currently, I am in the process of developing a drag and drop UI builder for react-based app frameworks. Before incorporating drag and drop functionality, my main focus is on rendering a page layout based on a structured array stored in the state. I have a ...

Angular custom filter applied only when a button is clicked

I have recently started exploring angular custom filters and I am curious to know if there is a way to trigger the filters in an ng-repeat only upon clicking a button. Check out this example on jsfiddle : http://jsfiddle.net/toddmotto/53Xuk/ <div ...

Updating Hidden Field Value to JSON Format Using jQuery and JavaScript

var jsonData = [{"Id":40,"Action":null,"Card":"0484"}]; $('#hidJson', window.parent.document).val(jsonData); alert($('#hidJson', window.parent.document).val()); // displays [object Object] alert($('#hidJson', window.parent.doc ...

Steps for eliminating curly braces and renaming the key-value pairs in a JSON object

I have a JSON output that looks like this: { "intent": "P&P_Purchase", "value1": { "date1": "30-Dec-19", "prd_desc": "NEEM UREA OMIFCO (45 KG)", "qty": &quo ...

Implementing Ajax Like Button functionality in a Ruby on Rails application

I have a Ruby on Rails project that includes a User model and a Content model, among others. I recently implemented a feature where users can "like" content using the acts_as_votable gem. Currently, the liking functionality works as expected but it requir ...

Refresh the html page periodically by utilizing ajax every X seconds

Recently, I came across a post discussing the topic of automatically refreshing an HTML table every few seconds. The post can be found here. Currently, I am working with Rails and I want to achieve a similar functionality. However, I specifically want to ...

Uploading pictures to a directory and storing their filenames in a database with the help of PHP

I'm facing a challenge trying to upload 2 files into a folder and save their names and image paths in a database. Below is my HTML code for reference: <input class="field2" type="file" name="file[]" multiple="multiple" /> Here is the PHP code ...

Tips for modifying AJAX behavior or restricting requests in Wicket

I am looking to prevent updates based on a specific JavaScript condition using AjaxSelfUpdatingTimerBehavior. WebMarkupContainer messagesWmc = new WebMarkupContainer( "messagesWmc" ) ; messagesWmc.setOutputMarkupId( true ) ; messagesWmc.add( ...

Tips for formatting input boxes on the client side

Q: How can I format my textbox so that when a user enters a number, such as one, it will be displayed as 0000001? The goal is to have any number entered be shown in 7-digit format. ...

position an element at a higher level than the #top-layer

I developed a custom tool and utilized z-index to position it above all other elements: .customTool { position: fixed; z-index: 99999; } However, this functionality stops working when a modal <dialog /> element is opened in modal mode. As a res ...