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

The absence of underlines for <a href> and <u> is causing an issue

Below is a snippet of code that I am working with: echo "<form> <div id=\"error\"align=\"center\">"; echo "You've either entered the incorrect <b>username</b> or incorrect <b>passwor ...

Utilizing Bootstrap Modal to Display PHP Data Dynamically

Modals always pose a challenge for me, especially when I'm trying to work with someone else's code that has a unique take on modals that I really appreciate (if only I can make it function correctly). The issue arises when the modal is supposed ...

To determine whether a variable is an integer in PHP

Is there a more elegant solution to this problem? if( $_POST['id'] != (integer)$_POST['id'] ) echo 'not an integer'; I attempted if( !is_int($_POST['id']) ) However, I encountered issues with is_int(). This ...

Reduce the noise from different versions by utilizing package-lock.json

There may not be a clear-cut answer, but I'm curious to hear how others handle the issue of package-lock.json causing problems when committing to their node repository. Many opinions lean towards committing package-lock.json - ensuring consistent dep ...

A new ASP.NET MVC-5 web application is missing the class definition for "input-validation-error."

I recently created a new ASP.NET MVC-5 web application using Visual Studio 2013. When I attempted to use the built-in login form and left the required fields empty, I noticed that the fields were not highlighted in red as expected. After inspecting the ge ...

Fetching JSON data from an external URL using AngularJS

Check out this URL that shows JSON data in the browser: I attempted to store the data in a variable with the following code: $http.get('http://api.geosvc.com/rest/US/84606/nearby?apikey=4ff687893a7b468cb520b3c4e967c4da&d=20&pt=PostalCode& ...

Using Javascript to eliminate divs on a page that have the attribute display:none

Looking for a way to remove generated divs with display: none using JavaScript? Let's find a solution. <div id="workarea"> <div id="message" class="messages" style="display: none;">Your message was saved</div> <div id="message" c ...

How can you determine if all specified events have been triggered in jQuery?

I am implementing custom triggered events following asynchronous calls, and I'm in need of a method to determine when all the events have been triggered. For instance: var ajaxCall1 = function(){ $.ajax({ url: "someUrl.html", com ...

When I click the login button, a .ttf file is being downloaded to my computer

I have encountered an issue with my web application where custom font files in .ttf, .eot, and .otf formats are being downloaded to users' local machines when they try to log in as newly registered users. Despite attempting various solutions, I have b ...

Customizing CSS based on URL or parent-child relationship in WordPress

I'm having trouble finding a solution for what seems like a simple issue... Currently, my header has a border-bottom and I'd like to change the color of this border based on the section the user is in. For example, consider these parent pages: ...

Different method for adding child elements to the DOM

When creating a DOM element, I am following this process: var imgEle = document.createElement('img');     imgEle.src = imgURL;             x.appendChild(imgEle); Instead of appending the last line which creates multiple img elements ev ...

A custom script developed to detect the presence of the numeric combination "11" and promptly notify the

I am attempting to develop a unique chrome extension that detects typing errors in orders. For example, if the user accidentally types "11" instead of "1", an alert should be triggered. However, I am encountering an issue where the script is running in an ...

Display/Modify HTML form

Looking for advice on how to create an interactive HTML form that displays data and allows users to edit it by clicking 'Edit' before submitting changes. Any suggestions on how to implement this functionality? ...

Why is it that comparing the childNodes of two identical nodes results in false, while comparing their innerHTML yields true?

Currently, I am in the process of developing a simple function in Node.js that compares two DOMs. My goal is to not only identify any differences between them but also pinpoint the exact variance. Interestingly, upon reconstructing identical DOMs using jsd ...

What could be causing the incorrect updating of React State when passing my function to useState?

Currently, I am in the process of implementing a feature to toggle checkboxes and have encountered two inquiries. I have a checkbox component as well as a parent component responsible for managing the checkboxes' behavior. The issue arises when utiliz ...

execute the command only if all ava tests succeed

I'm working on creating an npm script that will execute Ava, and if it is successful, will then run another deploy command. Is there a way to obtain the result of an Ava test in JavaScript, or to save it to a file or pass it to a subsequent command? ...

Sometimes, the page-wide background in Internet Explorer doesn't load properly

Currently, I am working on a website that uses an image as the background for the entire site. Everything seems to be running smoothly in Firefox and Safari, but Internet Explorer is giving me some trouble. Sometimes the image fails to load at all, other t ...

What is the process for getting the input value when a key is released?

My goal is to capture the actual value or text from an input field and store it in a variable. However, when I use the console to check the output, it shows me a number indicator that increments each time I type something. <input id="usp-custom-3" ty ...

`Inconsistencies between Postman and AngularJS service responses`

When I make a call to the endpoint using Postman, I receive this response: https://i.stack.imgur.com/pH31G.png However, when I make the same request from my AngularJS service defined below: this.login = function (loginInfo) { return $http({ ...

Creating an array inside a Vue function

Currently, I am facing a challenge with restructuring an array in Vue.js. I am able to log the values within my method and push them into an array, but I'm struggling to format the array as required. The desired structure of the array should be like ...