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

Declaring a Javascript variable within an if statement does not alter the value of the global variable

Currently, I am working on enhancing my HTML projects by using JavaScript to modify the video source. Below is the video element in question. <div> <video id="songVid" onmouseover="controlsVid()"> <source src=&qu ...

Slider that is always being updated cannot be moved by dragging

Currently, I am utilizing React wrapped with cljs+reagent to develop a small application. One key feature I require is a slider that updates roughly every second and can be adjusted by the user. At present, my implementation looks like this: [:div.scrubb ...

Moving from one section to the next within a web page

I am looking to add animation to my web app. When clicked, I want to move only the ID table column from one div to another div while hiding the other column. However, I am struggling with figuring out how to animate the movement of the ID column (from the ...

How can you exclude selected values in React-select?

Here is how I have defined my select component: this.state.list = [{label: "test1", value:1}, {label:"test2", value:2}, {label:"test3", value:3}] this.state.selected = [{label:"test2", value:2}] let listMap = this.state.list let list = this.state.list { ...

Uploading files asynchronously in Internet Explorer 8

Currently, I am on the lookout for sample code that allows asynchronous file uploads in IE8 using Ajax. While having upload progress would be a bonus, it is not essential. Moreover, I specifically need PHP code to handle the uploaded files on the server ...

Reload the webpage locally without sending a request to the server

My goal is to refresh the browser window without needing to hit the server. I am considering using javascript for this task. Below is the code that I have, but I'm not entirely clear on what it does! <body onload="JavaScript:AutoRefresh(5000);"> ...

How to sort data in AngularJS by clicking on a column to change the order from ascending to

The code view below is what I am currently working with: <tr ng-repeat="c in clients | orderBy:'code'"> <td>{{c.firstname}} {{c.lastname}}</td> <td>{{c.telephone}}</td> <td>{{c.location}}</td> ...

What could be causing the absence of req.body data in a specific route in my Node JS application?

Hello, I am encountering an issue with my Node JS application: When attempting to authenticate, I am receiving an "undefined" value for "req.body.username" upon sending a POST request to that specific route. This problem seems to only occur on this parti ...

Placing a div above the navigation bar in jQuery Mobile to create multiple stacked footers

I am currently facing an issue with my website where I have a static nav bar at the bottom of each page, but I need to add another content div above it. When I try to position it as a footer, it ends up in the same spot as the nav bar. Absolute positioning ...

Does jQuery provide a counter function to ajaxComplete?

I'm curious if there exists a jQuery function that acts as the counterpart to ajaxComplete? I am looking for something that can be triggered before the ajax event, similar to beforeSend $( document ).ajaxComplete(function( event, xhr, settings ) { ...

JavaScript incorrectly constructs date strings

Hey there, I've been attempting to create a JavaScript date object using a string but for some reason, it's consistently off by one day. Every time I try, it ends up showing the wrong day. Below is the code snippet in question: var date = new Da ...

Error encountered: EPERM when attempting to rename a directory in Node.js unexpectedly

There is a requirement for me to remove the Backup folder, rename the processor as Backup, create a Processor folder again, and send a response to the user. The code I am using for this task is as follows: fsExtra.remove('app/Backup', function(e ...

What could be the reason for the React component not re-rendering even after its prop has been updated?

One of the challenges I'm facing with an application I'm currently working on is a re-render issue. To simplify, let's say we have two components - DisplayElement1 and DisplayElement2. In this scenario, DisplayElement2 iterates through a ba ...

Organizing list items into vertical columns

Could you help me with UL/LI syntax and how to create a wrapping list? For example, I would like to display: 1 2 3 4 5 6 As: 1 4 2 5 3 6 Currently, I have a header, content, and footer all set with specified heights. I want the list to wrap when ...

Text area containing an unspecified value within a webpage featuring interactive forms

I'm struggling to understand why I can't access the field values on forms that are generated dynamically through AJAX and MySQL. The structure of the form template is as follows: <form class="dishform" id='" + d.dish_id + "FF' acti ...

Encountering a challenge while rendering an Ajax partial using link_to to specify a controller action

I am facing an issue with rendering different partials into a div (id="content") on a "proposition" show page. The partial to be rendered depends on the selected tab at the top of the div. To achieve this, I have been attempting to use AJAX and the follow ...

Utilizing JS Underscore for combining and organizing arrays with common keys

I am facing a scenario where I have two arrays: "array_one": [ { "id": 1, "name": One }, { "id": 2, "name": Two } ] "array_two": [ { "id": 1, "name": Uno }, { "id": 3, "name": Three ...

Adapt the dimensions of the iframe to perfectly match the content within

Looking for a way to dynamically adjust the size of an iframe to perfectly fit its content, even after the initial load. It seems like I'll need some kind of event handling to automatically adjust the dimensions based on changes in the content within ...

Using CSS, center a div element both vertically and horizontally, and position the footer at the bottom of the page

I am encountering some unexpected behavior for a task that I thought would be simple. I have two main objectives in mind. Firstly, I want the footer to be displayed at the bottom of the page as an actual footer. Secondly, I need the div with the ".center-d ...

Passing Data from $http.get to Angular Controller Using a Shared Variable

One issue I'm facing is the inability to pass the content of a variable inside $http.get() to the outside scope, as it always returns undefined. I attempted using $rootScope, but that approach was not successful. controller('myControl', fu ...