How do I delete the final row from a table and position it as the first row using javascript?

In the function downward(), I attempted to remove the last row of a table and insert it as the first row, while the display() function simply generates the table.


<body>
<script>
function downward() {
    var table = document.getElementsByTagName('table');
    var count = table.rows.length - 1;
    var currentTable = table[count];
    var rows = currentTable.getElementsByTagName('tr');
    var shifted = rows[count];
    rows[count].parentNode.removeChild(rows[count]);
    currentTable.insertBefore(rows[0]);
}

function display() {
    var table = document.createElement('table');
    table.setAttribute("id", "tbl");

    for (var i = 0; i < 4; i++) {
        var tr = document.createElement('tr');
        for (var j = 0; j < 4; j++) {
            var td = document.createElement('td');
            var text = document.createTextNode(j+i);
            td.appendChild(text);
            tr.appendChild(td);
        }
        table.appendChild(tr);
    }
    document.body.appendChild(table);
}
</script>
<input id="display" type="button" value="Display" onclick="display();" />
<input id="downward" type="button" value="downward" onclick="downward();" />
</body>

Answer №1

Utilize the .removeChild method to eliminate the last child node and then insert it before the first element with the assistance of the .insertBefore function. Check out this illustration:

function myFunction(){
var table = document.getElementById("myTable");
var tr = document.getElementById("myTable").lastChild;
table.removeChild[document.getElementsByTagName("tr").length];
table.insertBefore(tr, document.getElementById("myTable").firstChild);
}
<table><tbody id="myTable"><tr><td>1</td></tr><tr><td>2</td></tr><tr><td>3</td></tr></tbody></table>
<br>
<button onclick="myFunction()" value="click me to see the result">click me to see the result</button>

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

"Experiencing a callstack overflow due to multiple carousels on one page using Jquery or Vanilla

Currently, I am working on implementing a Jquery infinite autoplay multiple carousel. What I have done is created two separate carousel blocks on the same page within the body section. <div class="rotating_block"> <div class="bl ...

Utilizing JSON data in JavaScript to populate a datatable

After receiving a JSON result from an AJAX jQuery call, I stored it in a variable and attempted to insert the JSON data into a datatable. However, instead of inserting the data from the variable as intended, the datatable is currently populated with JSON d ...

Update the text in a personalized dropdown menu when an option is chosen

After spending some time working on a customized dropdown with the use of CSS and Vanilla JavaScript (Plain JS), I encountered an issue while trying to select and update the dropdown text upon clicking an option: window.onload = () => { let [...opt ...

When attempting to call a function from a separate JavaScript file in Vue, the returned value is showing

My goal is to trigger my notification function from another JS file, but I keep getting an undefined error. The code snippet for the notification function in notification.js is as follows: function notification(message, level = 'success') { ...

One can only iterate through the type 'HTMLCollection' by utilizing the '--downlevelIteration' flag or setting a '--target' of 'es2015' or above

I'm currently working on developing a loader for my static grid. I've incorporated the react-shimmer-skeleton package source code, but I'm encountering issues with eslint in strict mode. You can find the respective repository file by followi ...

Issue with Ajax form submission on one specific page

My form submission using JQuery AJAX is causing my page to redirect to submit.php instead of staying on the current page. I have tried various solutions but cannot pinpoint the issue... The PHP script seems to be working fine, with only one echo statement ...

Experimenting with React components that showcase various components in a loop

Currently, I am working on a react-native app where I have a simple component that receives an array and displays it as markers on a map using react-native-maps. My goal is to write tests for this component. The test should verify that there is a marker p ...

The code functions properly when run locally, however, it encounters issues when deployed

When testing the following lambda code locally using Alex-app-server, everything works perfectly fine. However, when I publish it and test on AWS Lambda, it gets stuck within the else statement. It prints the console log 'OUT PUBLISH' but doesn&a ...

Iterate through and remove elements within an array containing objects

Within my Vue.js application, I am working with an array of objects that I need to iterate through and display in the web browser. The array consists of four objects, but I only wish to show three based on a user's preference setting stored in a varia ...

Displaying all components simultaneously instead of displaying placeholders and awaiting image downloads

Is there a way to instruct the browser to load all images first before displaying the page, rather than rendering img elements and then loading the images afterwards? I am working with asp.net on the server side, but I believe the solution may involve DOM ...

The cursor seems to be playing a game of hopscotch every time I

In the text box, I've implemented a feature to prevent typing of a forbidden character: #. While this feature is successful in restricting the input of the forbidden character, there's an issue that arises when data is already filled in the text ...

Creating a column chart with dynamic data in Angular using Highcharts

I have successfully integrated high charts in angular js using hard coded data. However, I am facing an issue when trying to display dynamic data fetched from a web service. In my controller: $scope.months = []; $scope.retail = []; $scope.wholesale = []; ...

Working with Angular's forEach method and handling null values

I'm encountering an issue where the array of selected devices is not getting the values when attempting to add multiple devices to a group. Can someone identify the problem or suggest an alternative method? I referred to http://www.dotnetawesome.com/2 ...

Encountering an issue with compiling Angular due to a Type Inference error

interface Course { name: string; lessonCount: number; } interface Named { name: string; } let named: Named = { name: 'Placeholder Name' }; let course: Course = { name: 'Developing Apps with Angular', lessonCount: 15 }; named = ...

Understanding the scope of jQuery variables within a function

myClass.prototype.toggle = function() { var elements = []; $.getJSON('http://localhost/jsoner.php', function(data) { $.each(data, function(index, value) { elements.push(value); alert(elements[0]); //this is functioning } ...

When working with TypeScript, how do you determine the appropriate usage between "let" and "const"?

For TypeScript, under what circumstances would you choose to use "let" versus "const"? ...

Using the React context without explicitly setting the contextType or defining a default context

Is it possible to access the closest context from a provider without having to explicitly define contextType in a component by using this.context? Alternatively, is there a way to establish a default context so that when I use this.context, I automaticall ...

The array within the JSON object holds vital information [Typescript]

I have some data stored in an Excel file that I want to import into my database. The first step was exporting the file as a CSV and then parsing it into a JSON object. fname,lname,phone Terry,Doe,[123456789] Jane,Doe,[123456788, 123456787] Upon convertin ...

Parsing Json data efficiently by utilizing nested loops

I have 2 different collections of JSON data, but I'm unsure of how to utilize JavaScript to parse the information. Data from API1 is stored in a variable named response1: [{"placeid":1,"place_name":"arora-square","city":"miami","state":"florida","c ...

What is the process for incorporating a class into a table within TinyMCE using JavaScript?

I am facing an issue with adding a class to a table. I'd like the following code: <table></table> to transform into this code by clicking a button in tinymce. <table class="try-class"></table> I have added a button, bu ...