The battle between CSS and jQuery: A guide to creating a dynamic zebra-style table without relying on additional plugins

Is there a better way to create a dynamic zebra styling for table rows while still being able to hide certain elements without losing the styling? In this code snippet, I'm using the CSS :nth-of-type(even) to style even rows but running into issues when hiding specific rows. How can I achieve this in a more efficient manner?

<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <style type="text/css">
    table tr:nth-of-type(even){background: yellow;}
  </style>
  <script type="text/javascript">
    function hideRow(){
      $(".hidden").hide();
    }
  </script>
</head>
<body>
<center>
 <table cellspacing="0" border="1">
     <tbody>
    <tr class="table-row">
      <td>row1</td>
    </tr>
    <tr class="table-row">
      <td>row2</td>
    </tr>
    <tr class="table-row hidden">
      <td>row3</td>
    </tr>
    <tr class="table-row">
      <td>row4</td>
    </tr>
    <tr class="table-row">
      <td>row5</td>
    </tr>
    </tbody>
 </table>
 <input type="submit" onclick=" hideRow()" value="submit"/> 
 </center>
</body>
</html>

How can I dynamically alter the table's style based on certain conditions?

Сurrent result:

Expected result:

Answer №1

Even when an element is hidden, it still exists in the background, causing some problems. One solution to this issue is to use a simple script along with CSS :nth-of-type(even) selectors. Here are two classes that can be used:

.table_odd { color: pink; } 
.table_even {color: purple; }

Next, create a function:

function updateTableColors( $tableSelector ) {
    $tableSelector.find('tr:odd:not(.hidden)').removeClass('table_even').addClass('table_odd');
    $tableSelector.find('tr:even:not(.hidden)').removeClass('table_odd').addClass('table_even'); 
}

Using this function is straightforward. Call it on document ready and whenever you hide an element:

updateTableColors( $('table') );

Answer №2

For replacing the use of hide(), consider using remove() instead. Here is an example:

$('input[type="submit"]').click(function(){
    $(".hidden").remove();
});

Explore this demo link: http://jsfiddle.net/fhbgM/

Answer №3

 div[class=content] ul:nth-child(odd){background-color: lightblue;}

Do you think this code will have the desired effect?

Note: Not yet tested on live environment

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

Safari browser removes spaces after commas in cookie values

I'm encountering an issue when trying to set a session cookie for storing an Address. It seems that whenever I include a comma followed by a space in the cookie's value, Safari automatically removes the spaces after the commas, causing the format ...

Can you choose the class that has not yet been seen before?

Imagine a scenario where the following code is present: <div class="a"> <div>1</div> <div>2</div> <div> <div> <div class="b">3</div> </div> ...

Implementing dynamic https URL embedding in AngularJS based on the user's browser location

When my webpage built with angularjs is launched using https, all urls within the page should also use https instead of the default http. Is it possible to make angularjs use either http or https based on the initial request? Here are some example embedd ...

The CSS class is specifically assigned to a single element

After every two seconds, my JavaScript function is triggered and based on certain logic, I aim to add a CSS class with an effect to an HTML element on the page. var counter = 0; $interval(function () { counter++; ...

Understanding conditional statements in JavaScript can greatly enhance your programming skills

Here's a search component that I've been working on. I'm trying to figure out how to handle the scenario where there are no items in the array. Should I use an if statement or is there another approach I should take? Any help would be greatl ...

Where can I locate htmlWebpackPlugin.options.title in a Vue CLI 3 project or how can I configure it?

After creating my webpage using vue cli 3, I decided to add a title. Upon examining the public/index.html file, I discovered the code snippet <title><%= htmlWebpackPlugin.options.title %></title>. Can you guide me on how to change and cu ...

Troubleshooting Variable Issues in PHP and JavaScript

On my PHP page, I have a while loop where I am retrieving the following... print $divLeft.strip_tags($row->twitterUser)."?size=normal\"/><br \/>".$row->twitterUser.$divRight."<a href='javascript:void(0);' id=&apos ...

Exploring the realm of Angular templating and routing combined with the power

Currently, I am in the process of developing my very first Angular website that involves templating and routing. My goal is to have an image on the page that spans the entire window size minus 70 pixels. //Using Jquery (This particular section functions ...

retrieving XML information into a div using Ajax and JavaScript

I am currently working on developing a chat application and facing an issue with fetching all logged in users into a div with the ID "chat_members". Despite confirming that the XML file structure is correct, the JavaScript code alongside AJAX does not seem ...

What is the significance of Fawn's statement, "Invalid Condition"?

Despite following the instructions and initiating Fawn as stated in the document, I'm still encountering an error message that says Invalid Condition. Can anyone help me identify what is causing this issue? Thank you to all the helpers. await new Fawn ...

Looking for a way to ensure a div reaches 100% height within a specified area without exceeding the boundaries of the body?

I am working with jQuery mobile and have specific requirements for my project: The main content will be a large graphic that needs to fill the entire page, with both horizontal and vertical scrolling if necessary. The header should remain fixed at the to ...

The image slider is blocking the dropdown functionality of the navbar on mobile devices

My code is experiencing a conflict of events. I have created a menu bar using nav bar, as well as an image slider called the caroussel. The issue arises when the window is minimized - the menu bar fails to drop down properly with the presence of the caro ...

Which component from the Bootstrap library would be best suited for my needs?

I am looking to create a basic 6-page website. Here is the code for my main page: <html> <style> .ali{ width:170px; text-align:center; } footer{ background:#333; color:#eee; font-size:11px; padding-top: 25px; p ...

I can't seem to get my JavaScript to connect to my HTML file. What should I do next?

I'm facing a major issue at the moment. My HTML file doesn't seem to be linking properly with my JavaScript file, even though they are located in the same folder. The script link is correctly placed in the HTML file, but for some reason, it just ...

Whenever I try to send multiple forms along with their data using JSON/AJAX, I keep running into a parsing

My website features a jQuery accordion plugin. To gather form data from multiple forms, I am using the following code: $('#form_values').val($('form').serialize()). The collected data is then submitted to my PHP file which includes: &l ...

AngularJS's support for html5mode on GitHub pages is now available

Is it feasible for GitHub pages to accommodate AngularJS in html5mode? I came across a source online suggesting that it can be done with a fallback page for 404 errors. However, this solution seems flawed as it may result in multiple 404 errors, which wou ...

Working with Garber-Irish in Rails: Streamlining Administration and Keeping Code DRY

I am currently implementing the innovative garber-irish technique to organize my JavaScript files. Here's my issue: I have a Model (let's call it Item) with an init function located in app/assets/javascripts/item/item.js For example: MYAPP.ite ...

"Hidden panels in Sencha Touch only respond to show() and hide() methods after a resize event

Check out this demonstration of a Sencha Touch app by visiting this link. The button located in the bottom-left corner is supposed to show or hide the menu panel on top of the "Location info goes here" bar, but it seems to be functioning in an unexpected m ...

Interactive table on click

Seeking assistance with an issue involving a combobox (select) and a dynamic table generated from PHP. The table displays names along with their Firstname, Lastname, and ID (hidden). Upon clicking on a row in the table, I should retrieve the ID of that spe ...

Issue with margin-top on <p> and <a> elements not displaying correctly?

I've been attempting to incorporate margin-top for a link button, but unfortunately it's not working as expected. I've even experimented with inline styles for both the 'p' and 'a' tags. There are three list elements, I ...