BMay
BMay

Reputation: 3

JQuery Looping a slice(), split(), and wrapped array...for each element of class

I'm pretty sure I'm close to this one but i just can't seem to get it right. Im getting the following strings dynamically for each event listed, always in the same format. basically need to split() off the Date for each of these entries and return only the times, which are split() at the ',' and rendered in spans This is what I've got:

<div class="date">Di 22.10.2014 um 14:00, 18:00</div>
<div class="date">Di 22.10.2014 um 14:00, 18:00, 20:00 </div>

and

var data =$('.date').html().slice(17);
var arr = data.split(',');
$(".date").empty();
$.each(arr, function(i, v) { 
$('.date').append($("<span>").html(v));
}); 

.... so far so good... this http://jsfiddle.net/MealaBmay/K3D6d/1088/ is working, BUT I've realised each '.date' was ending up with the same content. I can't seem to get this script converted to do this for each ... I looked at Splitting text and wrapping each of the words in elements in jQuery and tried to use the same method....but sigh keep drawing a blank...any helpers out there? thx

Upvotes: 0

Views: 2280

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388406

Use the setter version of .text() which takes a callback function

$('.date').each(function(i, text) {
  var $this = $(this),
    data = $this.text().slice(17);
  var arr = data.split(',');
  $this.empty();
  $.each(arr, function(i, v) {
    $this.append($("<span>").html(v));
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="date">Di 22.10.2014 um 14:00, 18:00</div>
<div class="date">Di 22.10.2014 um 14:00, 18:00, 20:00</div>


Probably another way to do the same

$('.date').html(function(i, html) {
  return $.map(html.trim().substring(17).split(','), function(item) {
    return '<span>' + item + '</span>'
  }).join('')
})
.date span {
  border: 1px solid lightgrey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="date">Di 22.10.2014 um 14:00, 18:00</div>
<div class="date">Di 22.10.2014 um 14:00, 18:00, 20:00</div>

Upvotes: 1

Related Questions