19eggs
19eggs

Reputation: 195

jquery wrap elements with div

Gurus,

I have this.

<td style="width:100px">
Queued:465
Rejects:3897
Offers:31
</td>

and need to make it as

<td style="width:100px">
<span class="label">Queued:</span><span class="data">465</span> <br>
<span class="label">Rejects:</span><span class="data">3897</span><br>
<span class="label">Offers:</span><span class="data">31</span>
</td>

Instead of one single line (Queued:465 Rejects:3897 Offers:31), I want to give a break after the numbers(they are dynamic). Queued, Rejects, Offers are fixed.

This is what I tried with.

$('td:contains(Queued:)').html(function() {
    return $(this).html().replace('Queued:', '<span class="label">Queued: </span>');
});
$('td:contains(Rejects:)').html(function() {
    return $(this).html().replace('Rejects:', '<br><span class="label">Rejects: </span>');
});
$('td:contains(Offers:)').html(function() {
    return $(this).html().replace('Offers:', '<br><span class="label">Offers: </span>');
});

Upvotes: 0

Views: 96

Answers (2)

Doug
Doug

Reputation: 3312

You can also go down the .split route rather than the Regex route.

var $td = $("td"),
    rows = $td.html().trim().split("\n"),
    html = [];

for (var x=0; x<rows.length; x++){
  var line = rows[x].split(":");

  html.push(
    "<span class='label'>"+line[0]+":</span>"+
    "<span class='data'>"+line[1]+"</span>"
  );
}
$td.html(html.join("<br>"));

Edit: Fiddle

Upvotes: 0

VisioN
VisioN

Reputation: 145398

$("td").html(function(i, val) {
    return $.trim(
        val.replace(/[a-z]+/ig, '<span class="label">$&</span>')
           .replace(/\d+/g, '<span class="data">$&</span>')
    ).replace(/\n/g, "<br />");
});

DEMO: http://jsfiddle.net/dfRzY/

Upvotes: 4

Related Questions