Maximizing the efficiency of Java Script code

I am struggling with optimizing this JavaScript code that adds and removes classes based on the presence of a specific class in the next rows of a table. Can anyone provide some guidance on how to make this code more efficient?

  $(".showTR").click(function () {
    let currentRow = $(this).parent().parent('tr');

    for (let i = 0; i < currentRow.length; i++) {
        if (!currentRow.next("tr").hasClass('Row')) {
            currentRow.removeClass('Row');
            currentRow = currentRow.next('tr');
        } else {
            break;
        }
    }

    if(!currentRow.hasClass('Row')) {
        $(this).hide();
    }
});

This code is designed to iterate through each row in a table, checking if the next row has a specific class. If it does not, the class is removed from the current row and the loop continues until a row with the specified class is found.

Answer №1

To handle a situation where HTML code is not available, one can consider the following approaches:

Method 1

  • Start by navigating to the parent tr. This can be done using either .closest('tr') or .parents('tr').
  • Retrieve the list of all subsequent tr elements using .nextAll('tr').
  • Iterate through each of these elements and verify their value. If a specific element has a certain class, remove it and set a flag to prevent affecting other tr elements.
  • If the last tr element is encountered, also hide .showTR.
$(".showTR").click(function() {
  var self = this;
  var hasUpdated = false;
  var trs = $(this).parents('tr').nextAll("tr");
  $.each(trs, function(i, tr) {
    if (!hasUpdated) {
      var $tr = $(tr);
      hasUpdated = $tr.hasClass('Row') && $tr.removeClass('Row') && true;
      if (i === trs.length - 1) {
        $(self).hide()
      }
    }
  })
});

Method 2

  • Obtain the first sibling tr relative to the parent tr that possesses the "Row" class.
  • Remove the class from this element.
  • If this element happens to be the last child, hide .showTR.
$(".showTR").click(function() {
  var tr = $(this).parents('tr').next("tr.Row:first");
  if(tr.length){
    tr.removeClass("Row");
    if(tr.is(':last-child'))
      $(this).hide()
  }
});

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 upload directory in KCFinder can be accessed and selected using a URL

Issue: While using the link to open kcfinder as defined in kcfinder, I encountered a problem. The link is intended to open kcfinder with the provided parameters: window.open('/kcfinder/browse.php?type=files&dir=files/public&subDi ...

Step horizontally to scroll varying amounts

On my webpage, I have implemented two buttons to scroll left and right. When these buttons are clicked, the page should move left or right by the width of each individual div (since they all have different widths). I am unsure if this functionality can b ...

What is the best way to achieve a horizontally compact layout in Bootstrap by centering the content?

I am looking to center my content on the page and maintain a close proximity between items within a div. However, with Bootstrap 5, when I resize the page wider, additional space is added which pushes the items apart. Is there a way to keep them compacted ...

Troubleshooting padding problem in mobile gallery view with Bootstrap

Having a problem with the gallery layout in Bootstrap. It looks great on desktop view, but on mobile, there's no space between images on the same row. On mobile, the images stack vertically without any spacing between them within a row. However, ther ...

Having issues with the addClass() method in JavaScript not functioning properly on hover

Coding Challenge <ul class="navBarExtended"> <li><a href="#">Link</a></li> </ul> Styling Solution .onHover{ text-decoration: underline; } Interactive Scripting $("ul.navBarExtended li a").hover( function() ...

What is the best way to achieve complete transparency for an input element?

Is there a way to make the input element completely see-through, allowing the body background image to show through instead of the parent's background color? Sample HTML code: body{ background-image:url("https://upload.wikimedia.org/wikipedia ...

Enable the input field once the checkbox has been marked

Here is a checkbox example: <div class="form-group"> <input type="checkbox" id="examination" class="form-control" name="exam" placeholder="Enter Title"> <label>Enable Exam</label> </div> Additionally, I have a disabled inpu ...

Top method for developing a cohesive single-page application

Many websites are incorporating JSON data in string format within their page responses, along with HTML: For example, take a look at The benefit of rendering JSON in string format within the page response is that it allows for the efficient loading of da ...

The alignment of my card icons changes depending on the size of the paragraph

Here are my cards I am attempting to give them a relative position and the parent div an absolute position, but it is not working as expected. Despite several attempts, I still cannot get the desired result of positioning the cards correctly within the p ...

Delay the rendering of the MUI DataGrid column until after the DataGrid is visible on the screen

Would it be feasible to asynchronously load a column of data in the MUI DataGrid after the table is displayed on the screen? Retrieving this additional data from the database is time-consuming, so I aim to have it appear once the table has fully loaded. T ...

Assistance needed with dynamically resizing a background image

Is there a way to automatically adjust the size of a background image for an element? For instance, I want my links in HTML to have a background image with slanted borders and rounded corners. Usually, you would set the width of the anchor element to fit t ...

Creating a dynamically changing AppBar component in material-ui-next React that responds to scroll events

Following the Material Design guidelines, the top app bar should exhibit specific behavior: When scrolling, the top app bar can [...] undergo the following changes: - Scrolling upwards hides the top app bar - Scrolling downwards reveals the top ...

Flask: BadRequestKeyError: 400 Bad Request: The server was unable to comprehend the request sent by the browser (or proxy)

When I try to link to the edit view in my birthday reminder app, I keep getting a key error. The get_Gift function returns an object with the key field present and the HTML form has all the necessary fields, so I'm not sure why this error is occurring ...

Learning the basics of JavaScript: Displaying the last number in an array and restarting a function

Hey there, I'm diving into the world of JavaScript and have set myself a challenge to create a simple bingo number machine. Check out my CodePen project here. I've successfully generated an array of 20 numbers, shuffled them, and added a marker t ...

How to make a letter stretch all the way down the paper?

As I'm creating a table of contents for my website, I was inspired by an interesting design idea that I came across: I am particularly drawn to how the T extends down and each section is numbered with the title wrapped around it. How can I achieve th ...

Using knockout to data bind a function to an onclick event that takes in multiple parameters

I've scoured the internet and experimented with various methods, but I'm encountering an issue where the click function intermittently fails to fire. Below is my HTML code snippet: <input type="radio" data-bind="checked:a, checkedValue: 0 ...

programming / mathematics - incorrect circular item rotation

I need help arranging a sequence of planes in a circular formation, all facing toward the center. However, I seem to be experiencing issues with the rotation after crossing the 180-degree mark. While my objects are correctly positioned around the circle, t ...

Steps to easily modify the color of Font Awesome stacked icons when hovering over them

I have incorporated two Font Awesome icons into my design: fa-circle-thin fa-user-plus These icons are stacked to create a circular icon appearance. <span class="fa-stack fa-sm"> <i class="fa fa-circle-thin fa-stack-2x"></i> <i c ...

Toggle the visibility of text boxes based on the checkbox selection

After doing some research, I decided to revise the question after receiving feedback that it was causing some concern. When a checkbox is clicked, the content of the corresponding div should be visible and vice versa. How can I achieve this? Thank you. JQ ...

issue concerning slide functionality and ajax integration

I'm facing an issue with the structure of my HTML. Here is the setup I have: <div id ="slide1"> <form method="post" id="customForm" action=""> //my content - name, email, mypassword, pass2 </for ...