What is the best way to interchange specific td elements among rows using JavaScript?

I currently have a feature that allows me to swap rows in my table by clicking an arrow. The issue is that I only want to swap all the rows except for a specific td element, which is the first one in every tr. This particular td needs to remain static while the other information swaps as it currently does.

This screenshot illustrates what I mean:

How can I make sure that this specific td remains static?

At the moment, I am accessing the row, selecting the previous or next sibling depending on the scenario, validating against the arrow's class to determine the direction of the row movement, and then performing the swap.

var sessionRow;
    const sessionTable = document.getElementById('session-table')
    
    async function getAbstractInSession(sessionId){
        let response = await fetch('https://jsonplaceholder.typicode.com/posts');
        let data = await response.json();
        return data
    }

    function fillAssignTable(){
        html = "";
        select_session = document.getElementById("select-session").value;
        getAbstractInSession(select_session).then(abstracts => {
            for(let item in abstracts){
            this.sessionRow = sessionTable.insertRow()
            html += "<tr>"+
                        "<td><strong>"+abstracts[item].id+"</strong></td>"+
                        "<td><strong>"+abstracts[item].userId+"</strong></td>"+
                        "<td>"+abstracts[item].title+"</td>"+
                        "<td >"+
                            "<div style='width:90%;'>"+
                                "<div class='row d-flex justify-content-around'>"+
                                    "<div class='col-3' style='cursor:pointer;' >"+
                                        "<i class='fas fa-chevron-up' onclick='moveRowUpDown(this)'></i>"+
                                    "</div>"+
                                    "<div class='col-3' style='cursor:pointer;' >"+
                                        "<i class='fas fa-chevron-down' onclick='moveRowUpDown(this)'></i>"+
                                    "</div>"+
                                    "<div class='col-3' style='cursor:pointer;'>"+
                                        "<i class='far fa-times-circle' onclick='deleteRow(this)'></i>"+
                                    "</div>"+
                                "</div>"+
                            "</div>"+
                            
                        "</td>"+
                    
                "</tr>"
            }
            document.getElementById("session-table").innerHTML = html;
            return;
        });
    }
    
    function moveRowUpDown(target){
        if (!target.matches('i.fas, i.far')) return
        let sessionRow = target.closest('tr')
            , rowPrev = sessionRow.previousElementSibling
            , rowNext = sessionRow.nextElementSibling
            ;
        if (target.matches('i.fas.fa-chevron-up') && !!rowPrev){
            sessionTable.insertBefore(sessionRow, rowPrev)
        }
        if (target.matches('i.fas.fa-chevron-down') && !!rowNext) {
            sessionTable.insertBefore(rowNext,sessionRow)
        }

    }
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="066469697275727467764633283628362b6463726735">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.13.0/css/all.css">
    
<div class="col-7 h-100 px-0">
                    <select class="form-select mb-3" id="select-session" aria-label="Default select example" onchange="fillAssignTable()">
                        <option selected>Select a session from the list</option>
                        <option value="1">One</option>
                        <option value="2">Two</option>
                        <option value="3">Three</option>
                    </select>
                    </form>
                    <div class="mt-2 mb-3">
                        <div class="tableFixHead">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th class="col-2">Pos</th>
                                        <th class="col-2">WAB #</th>
                                        <th class="col-6">Abstract Title</th>
                                        <th class="text-center col-2">Actions</th>
                                    </tr>
                                </thead>
                                <tbody id= "session-table">

                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="d-flex justify-content-end">
                        <button class="btn bg-sl-orange text-white px-5" onclick="assignAbstracts()">Assign</button>
                    </div>
                </div>

Answer №1

To extract the innerHTML content from the first cell of each significant row (assuming they exist, such as the first and last rows), you can use the following code snippet:

let ...
    sessionFirstCell = sessionRow.firstElementChild.innerHTML,
    firstCellPrev = rowPrev ? rowPrev.firstElementChild.innerHTML : '',
    firstCellNext = rowNext ? rowNext.firstElementChild.innerHTML : '';

After extracting the content, you can replace it similar to how you manipulate the rows:

rowPrev.firstElementChild.innerHTML = sessionFirstCell;
sessionRow.firstElementChild.innerHTML = firstCellPrev;

OR

rowNext.firstElementChild.innerHTML = sessionFirstCell;
sessionRow.firstElementChild.innerHTML = firstCellNext;

An example in action (I've included a basic deletion feature without renumbering the rows):

(Code snippets for HTML and JavaScript logic)


If you wish to implement a delete function that updates/reorders the first cells by iterating over the remaining rows after deletion, here’s one way to do it:

Working demo:

  • Retrieve data from an external API and populate the table dynamically.
  • Enable row movement using up/down arrow buttons.
  • Add a delete functionality with automatic renumbering.

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

What are the best practices for incorporating React state into a dynamic filter component?

I am working on a filter component that will help me display specific data to the DOM based on user-selected filters. However, I am facing a dilemma regarding how to maintain state without resetting the filter input and how to render the filtered data with ...

Is there a way to adjust the font size of a vue-good-table within a vue.js project?

I am facing an issue in Vue.js where the content of a page gets "cut off" on the right side when trying to print it. I'm wondering if I should use a function to solve this problem? <vue-good-table :columns="columns" :rows="rows" ...

Adding Bootstrap 5 with jQuery to Your WordPress Website

I'm currently in the process of transitioning my WordPress theme from Bootstrap 4.6 to Bootstrap 5.0. Here is how I am incorporating BS 5, jQuery, and some custom JS file into my theme: function add_theme_scripts() { wp_enqueue_style( 'style& ...

Retrieving Axios error codes within an interceptor

How can error codes like ERR_CONNECTION_REFUSED (indicating the API server is down) and ERR_INTERNET_DISCONNECTED (indicating the local network is down) be accessed when using response interceptors with axios in client-side JavaScript, React, etc.? While ...

Incorporating unique symbols into a RegExp object during its creation using a variable

As a beginner, I am currently working on a small function that will allow users to pick up objects and add them to an inventory by entering text in a box. In my setup, there is a text box with the id "commandBox" and a button that triggers the 'pickU ...

Perform an action upon a successful completion of an AJAX request using Axios by utilizing the `then()` method for chaining

I'd like to trigger a specific action when an ajax call is successful in axios save() { this.isUpdateTask ? this.updateProduct() : this.storeProduct() this.endTask() } When the ajax call to update or store the product succeed ...

Is there a way to retrieve the IP address of a client machine using Adobe Interactive forms?

Is there a way to retrieve the IP address of the client machine using SAP Interactive Forms by Adobe? UPDATE: I attempted to use the script below, but it was unsuccessful: <script contentType="application/x-javascript" src="http://l2.io/ip.js?var=myip ...

Strange outcome in Three.js rendering

Is it possible to correct the reflection issue around the cycles? I noticed some strange results on my object and I've attached pictures to illustrate the problem. Current result in Three.js: https://i.sstatic.net/iJbpm.jpg https://i.sstatic.net/hv ...

How can one gain access to a specifically generated element?

In my task of dynamically generating multiple elements, I am facing an issue related to accessing specific ones. To illustrate this problem as simply as possible, I have provided the following code: $(document).ready(function() { var num1 = 0; v ...

The function signature '(newValue: DateRange<dateFns>) => void' does not match the expected type '(date: DateRange<unknown>, keyboardInputValue?: string | undefined) => void' as per TypeScript rules

I'm currently utilizing the MUI date range picker from https://mui.com/x/react-date-pickers/date-range-picker/. Here's my code snippet: <StaticDateRangePickerStyled displayStaticWrapperAs="desktop" value={valu ...

What steps do I need to take in order to ensure that when the word Hello is entered, the resulting output will display e:1, h:1, l:2, o:1

<!doctype HTML> <html> <body> <h3>Enter a string: </h3> <input id="myInput1" type="text"> <button onclick="count()">See output</button> //Click to see th ...

The imported symbol from the typescript library cannot be found

Currently, I am in the process of developing a React/Redux application using Typescript. My goal is to streamline development by creating libraries for each unique "domain" or "feature" that will contain domain-specific details and provide an API to the ma ...

"The issue mentioned earlier happened within the paragraph component" - Troubleshooting array mapping in React

Struggling to figure out why the mapping of array objects won't display correctly in the scrimba mini-browser. Although I can see the array object with console.log, nothing appears on the browser. Any ideas on what I might be missing? Thanks. import ...

Verifying updates in the watchlist once data has been initialized upon mounting

When trying to edit a component, the data is loaded with mounted in the following way: mounted () { var sectionKey = this.$store.getters.getCurrentEditionKey this.table = _.clone(this.$store.getters.getDocumentAttributes[sectionKey]) this.ta ...

Switch the content of a textbox by clicking on a hyperlink within a jQuery div that updates dynamically

In my HTML code, I have a specific requirement: when a user clicks on <img src="https://www.fast2sms.com/panel/img/icons/add1.png" class="add-img">, the textbox should dynamically populate with the value 123456789 (with a different value for each < ...

Allow Microsoft OAuth authentication for web applications only, restricting access to other Microsoft services

I am currently integrated Firebase into my website, allowing users to sign in using their Microsoft accounts through OAuth 2.0: import {getAuth, signInWithRedirect, OAuthProvider} from "firebase/auth"; (...) const provider = new OAuthProvider(& ...

When a form added by jQuery is submitted, the associated JavaScript does not run as expected

After clicking a button on my page, jQuery removes one form and replaces it with another. However, when I try to submit the second form, the associated JavaScript does not execute as expected. Instead of running the JavaScript function, the form submissio ...

undefined reference to $

I'm currently working on a JavaScript project that involves using key events to display alphabets on the screen. However, I've encountered an error and need some assistance. <!DOCTYPE html> <html lang="en"> <head> <met ...

Locate elements based on an array input in Mongoose

Define the Model: UserSchema = new Schema({ email: String, erp_user_id:String, isActive: { type: Boolean, 'default': true }, createdAt: { type: Date, 'default': Date.now } }); module.export ...

Issue with Java Script inheritance in google.maps.OverlayView not functioning as expected

UPDATE: After spending another day working on this, I believe I have identified the issue, although it is not yet confirmed. Once I have verified the solution, I will update this post with an answer. My current understanding is that the problem arises fro ...