Sam Skirrow Sam Skirrow - 1 year ago 82
Javascript Question

How to separate out elements in a string using jQuery each

I have made an Ajax call to an external site to grab some information from a specific element and return it on my site as a string.

This is the code for the AJAX call:

url: '',
type: 'GET',
success: function(res) {
var data = $.parseHTML(res);



This get's all the contents of a div called
on the external site and returns it looking like this:

<div id="credits">
<span class="creditYear">2010</span>, <span class="creditProductionType">Television</span>, <span class="creditCharacterRole">Cop Nicola Lanza</span>, <span class="creditProductionName">“Un posto al sole”</span>, <span class="creditCompany">Grundy</span>, <span class="creditDirector">Various</span><span class="creditYear">2008</span>, <span class="creditProductionType">Television</span>, <span class="creditCharacterRole">Lawyer Moroni</span>, <span class="creditProductionName">“Il Bene e il Male”</span>, <span class="creditCompany">Italy</span>, <span class="creditDirector">Giorgio Serafini</span>

Obviously, on my page this looks like a bit of a mess, what I'd like to be able to do is style it out nicely into a table. So for each set of results (i.e. year, production, character role, production name, company, director) there should be a row in a table, like this:

<td class="year"></td>
<td class="production_type"></td>
<td class="character_role"></td>
<td class="production_name"></td>
<td class="company"></td>
<td class="director"></td>
<td class="director"></td>

...but one row for each set of results. Would it be possible to append each corresponding credit (from the AJAX call) and display it in my table?

Answer Source

You could do it by copying the data in each of the spans to the relevant cells of a table:

In your success callback:

// Set up the table however you want it to be formatted
var $tableTemplate = $('<table><tr>' +
  '<td class="year"></td>' +
  '<td class="production_type"></td>' +
  '<td class="character_role"></td>' +
  '<td class="production_name"></td>' +
  '<td class="company"></td>' +
  '<td class="director"></td>' +

  // Copy the data from the request to a copy of the table
  var $newTable = $tableTemplate.clone();

  // And append it to your div (or whatever you want to put it in)