javascriptjqueryhtmljquery-append

Add div to the date showing in html and separate the days and month


I have some list of dates and I want to add div to the date and separate the days and months to a different div.

<div class="campaign">30/11/2016 - 
  <a href="#" target="_blank">Dummy Text</a>
</div>

I want to select and add div to the date. I also want to separate the days and months like this. Any help appreciated in advance.

<div class="campaign"> 
  <div class="date-wrapper">
    <div class="date">30</div>
    <div class="month">Nov</div>
    <div class="year">2016</div>
  </div> 
  <a href="#" target="_blank">Dummy Text</a>
</div>

I have tried the append method but I am not able select the date and store in a variable.


Solution

  • You can use .prepend( function ) to insert new HTML content in first of element.

    var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
      "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
    ];
    
    $(".campaign").prepend(function(){
      var dates = $(this).contents()[0].nodeValue.trim().match(/\d+/g);
      $(this).contents()[0].nodeValue = "";
      return '\
        <div class="date-wrapper">\
        <div class="date">'+dates[1]+'</div>\
        <div class="month">'+monthNames[+dates[0]-1]+'</div>\
        <div class="year">'+dates[2]+'</div></div> \
        </div>';
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="campaign">11/30/2016 - 
      <a href="#" target="_blank">Dummy Text</a>
    </div>