Alternating row colors using CSS zebra striping after parsing XML with jQuery

After successfully parsing XML data into a table, I encountered an issue with applying zebra stripe styling to the additional rows created through jQuery. Despite my efforts to troubleshoot the problem in my code, I remain perplexed.

Below is a snippet of the HTML code:

   
    <head>
    <title>Football Players</title>
    <style>
      table{
          border-collapse: collapse;
          border: solid 1px #dddddd;
          width: 500px;
      }
      th{
          text-align: left;
      }
    </style>

   </head>

<body>
  <table>
    <tbody>
      <tr>
        <th>Name</th>
        <th>Club</th>
        <th>Number</th>
        <th>Country</th>
      </tr>
      <tr>
        <td>Lionel Messi</td>
        <td>Barcelona</td>
        <td>10</td>
        <td>Argentina</td>
      </tr>
      <tr>
        <td>Juan Mata</td>
        <td>Manchester United</td>
        <td>8</td>
        <td>Spain</td>
      </tr>
    </tbody>
  </table>
</body>

Here is a section of the JQuery code:

   
$(document).ready(function () {
  $.ajax({
    type: "GET",
    url: "football_player.xml",
    dataType: "xml",
    success: processXML

  });

  function processXML(xml) {
    $(xml).find("football_player").each(function () {
      $("table tbody").append("<tr class = 'myClass'>");
      $("table tbody").append("<td>" + $(this).find("name").text() + "</td>");
      $("table tbody").append("<td>" + $(this).find("club").text() + "</td>");
      $("table tbody").append("<td>" + $(this).find("number").text() + "</td>");
      $("table tbody").append("<td>" + $(this).find("country").text() + "</td>");
      $("table tbody").append("</tr>");           
    });

    $("table tbody tr:nth-child(odd)").css("background-color", "#dddddd");
  }     
});

Lastly, here is the content of the XML file:

    
<football_players>
  <football_player>
    <name>Cristiano Ronaldo</name>
    <club>Real Madrid</club>
    <number>7</number>
    <country>Portugal </country>
  </football_player>

  <football_player>
    <name>Fernando Torres </name>
    <club>Chelsea </club>
    <number>9</number>
    <country>Spain</country>
  </football_player>

  <football_player>
    <name>Iker Casillas</name>
    <club>Real Madrid </club>
    <number>1</number>
    <country>Spain</country>
  </football_player>    

  <football_player>
    <name>David Beckham</name>
    <club>Los Angeles Galaxy</club>
    <number>23</number>
    <country>England</country>
  </football_player>
</football_players>

Answer №1

Make sure to always check the console for any errors. The issue in your code likely resides within the function processXML(xml). It seems that your <tr> tags were closed before adding the <td> elements, which is why the color was not being applied.

Try modifying it to...


 function processXML(xml) {
    $(xml).find("football_player").each(function() {
        $("table tbody").append("<tr class='myClass'>" + "<td>" +
            $(this).find("name").text() + "</td>" + "<td>" + $(this).find("club").text() + "</td>" + "<td>" + 
            $(this).find("number").text() + "</td>" + "<td>" + $(this).find("country").text() + "</td>" + "</tr>");
    }); // close processXML

    $("table tbody tr:nth-child(odd)").css("background-color", "#dddddd");
 }

Answer №2

With the help of Varun, I was able to implement the following solution successfully:

function parseXML(xml) {
    $(xml).find("football_player").each(function () {
      $("table tbody").append("<tr class='playerRow'><td>" + $(this).find("name").text() + "</td><td>" + $(this).find("club").text() + "</td><td>" + $(this).find("number").text() + "</td><td>" + $(this).find("country").text() + "</td></tr>");           
    });

    $("table tbody tr:nth-child(odd)").css("background-color", "#dddddd");
}

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

Creating a table with a tableHead cell comprised of multiple components in ReactJS/CSS using Material UI

It's possible that the title lacks description. I am attempting to generate a table with a specific layout like this Essentially, the "Average" cell is combined with two smaller cells for "height" and "width," which can be subdivided further. Unfortu ...

What is the method used by React or Next to prevent the <a> tag from refreshing the page while still loading content?

I'm currently diving into the world of NextJS and utilizing the Link component from the 'next/link' package. One thing that has been puzzling me is how the <Link> component ultimately renders an <a> tag with a href='/tosomew ...

Using jQuery and PHP to send a dynamic form through AJAX

I'm currently working on a pet registration form where users can add new pets. When a user clicks the "add pet" button, I use jQuery to clone the pet section of the form and give each cloned section an id like #pet-2, #pet-3, and so on. Although my ...

Preventing Cross-Site Scripting (XSS) when injecting data into a div

I am using Ajax to fetch data in JSON format and then parsing it into a template. Here is an example of the function: function noteTemplate(obj) { var date = obj.created_at.split(/[- :]/), dateTime = date[2] + '.' + date[1] + '. ...

The occurrence of an unanticipated character '#' was found

I'm currently facing an issue while using webpack to load dependencies. Whenever I execute the npm run dev command, I encounter the following error: Uncaught Error: Module build failed (from ./node_modules/babel-loader/lib/index.js): SyntaxError: ...

Having difficulty including my JavaScript file located in /app/assets/javascripts when using Rails 4 and "//= require_tree ." in application.js

I'm currently attempting to implement a d3.js graph into my Rails 4 application by following a tutorial found on this website. The example application provided on GitHub works perfectly as expected. The issue I am facing is that when I try to recreat ...

Using jQuery, encapsulate an image within a div element and transfer the floating style attribute from the image to the div

Can anyone assist me in wrapping an image within a div along with transferring the float setting? This is my current code: $('.photo-img').wrap('<div class="photo-wrap" />'); I would like the new div to inherit the float proper ...

Executing a Visual Basic subroutine from a jQuery dialog box

Currently, I have a form that includes a jQuery dialog creation. Within this dialog, there is a button generated from an ASP server control that should trigger a function in the code behind when clicked. However, I am encountering an issue where the functi ...

Mastering Jquery Isotope integration with Wordpress for seamless filtering

I've been struggling to implement isotope filtering in my project. As a beginner in jQuery/javascript, I wanted to integrate isotope functionality into a client's website. Despite researching extensively on Stack Overflow and various websites, I ...

Encountering a problem with populating data in postgresql

After executing the npm run seed command to populate data into PostgreSQL, even though the seeding process seemed to be successful, I couldn't locate the seeded data in the PostgreSQL database. Can anyone advise on what might have gone wrong or sugges ...

Styling elements using css and flexbox

Looking for some help with wrapping 4 items in CSS using flex. I want to display 3 items in a row, followed by a single item. .movies { display: flex; flex-direction: row; justify-content: space-between; align-items:flex-start; flex: 1 ...

Redirect the Submit button to the specified URL from the form element

Looking for a way to create a form with two fields: Username and Password. Upon clicking submit, the username and password should be added to the URL in a specific format. For instance: The URL structure will remain the same, only the "username_entered_i ...

Dependencies in Scala.js for CSS styling

I am currently having an issue implementing Scala.js with the bootstrap library. Including the js file was a simple and straightforward process: jsDependencies +="org.webjars" % "bootstrap" % "3.3.7-1" / "bootstrap.js" minified "bootstrap.min.js" However ...

Leveraging document.getElementById alongside css modules

When trying to retrieve an element that is using a css module, I encountered a problem where the id of the element changes after rendering. As a result, document.getElementById("modal") returns null. import React from "react"; export const HandleClick = ...

The WebView.HitTestResult method is currently only receiving <img src> elements and not <a href> elements

I am attempting to open a new window in the Android browser using "_blank". I have set up an event listener for this purpose. mWebView.getSettings().setSupportMultipleWindows(true); mWebView.setWebChromeClient(new WebChromeClient() { ...

ng-repeat not functioning properly when using track by, filter, and orderBy

I have come across this code snippet. http://jsfiddle.net/0tgL7u6e/ Scripting in JavaScript var myApp = angular.module('myApp',[]); function MyCtrl($scope) { $scope.nameFilter = ''; $scope.contacts = [ {name: 'G ...

NodeJS: Speed up your workflow by compressing video files

In my quest to enhance the performance of my application, I am seeking ways to compress images and videos to their smallest possible size without sacrificing quality. This process is known as lossless compression. While the imagemin package has proven eff ...

Show or hide the expand/collapse button based on the height of the container

Looking for a way to hide content in a Div if it's taller than 68px and display an expand option? The challenge lies in detecting the height of the responsive Div, especially since character count varies. I attempted using PHP to count characters bu ...

How can I keep a fixed position element from shifting to the left when resizing the window?

Is there a solution to prevent the logo element from shifting to the left when resizing the window, despite its fixed position? #logo { top:20px; left:50%; margin-left:-177.6px; width:355.2px; height:148.8px; ...

UI and `setState` out of sync

Creating a website with forum-like features, where different forums are displayed using Next.js and include a pagination button for navigating to the next page. Current implementation involves querying data using getServerSideProps on initial page load, f ...