Question

I'm pulling in data from a SharePoint list using SPServices. Each row from the list will be slotted into the container div with a class that corresponds to the month and year data from the list, like this:

<div class="container">
  <div class="child 07-2013">
    <p>Some content</p>
  </div>
  <div class="child 06-2013">
    <p>Some content</p>
  </div>
  <div class="child 06-2013">
    <p>Some content</p>
  </div>
  <div class="child 11-2012">
    <p>Some content</p>
  </div>
  <div class="child 11-2012">
    <p>Some content</p>
  </div>
</div>

I need to write a script (preferably jQuery rather than proper JavaScript as I'm more familiar with that) that will find the first of each class and add another div before it, so that it ends up like this:

<div class="container">
  <div class="header">July 2013</div>
  <div class="child 07-2013">
    <p>Some content</p>
  </div>
  <div class="header">June 2013</div>
  <div class="child 06-2013">
    <p>Some content</p>
  </div>
  <div class="child 06-2013">
    <p>Some content</p>
  </div>
  <div class="header">November 2012</div>
  <div class="child 11-2012">
    <p>Some content</p>
  </div>
  <div class="child 11-2012">
    <p>Some content</p>
  </div>
</div>

I know I could write something like this:

function addHeaders(){
  $('.07-2013').before('<div class="header">July 2013</div>');
  $('.06-2013').before('<div class="header">June 2013</div>');
  etc...
}

But the problem is that I don't want to define each class in the script, because data will be added to the SharePoint list constantly and I want to future-proof it so that the author can update the SharePoint List and the script will handle the data automatically.

So, is there any way to ambiguously find the first instance of each class within the container div?

Was it helpful?

Solution

Try

var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], flag = {}
$('.container > .child').each(function () {
    var month = this.className.match(/(\d{2})-(\d{4})/);
    if(flag[month[0]]){
        return;
    }
    flag[month[0]] = true;
    $(this).before('<div class="header">' + months[month[1] - 1] + ' ' + month[2] + '</div>')
})

Demo: Fiddle

OTHER TIPS

Rather than using $('.07-2013') in your function, you can refer to $(".child") which I found in all your divs.

And related to the text to be used in that div, you can make a script to return you month name corresponding to the number and append it by year in that DIV.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top