user1038620
user1038620

Reputation: 3

Add HTML To The Contents Of A Div Using jQuery

I am currently generating the following div:

<div class="dates" >November 18, 2011 7:30 pm November 19, 2011 7:00 pm  </div>

I want to use jQuery to on the load of the page change the div to read like this:

<div class="dates" >November 18, 2011 7:30 pm<br />November 19, 2011 7:00 pm<br /></div>

Wanted to get jQuery to change instances within the div of pm to pm<br />

Any ideas?

Upvotes: 0

Views: 115

Answers (6)

Rich O&#39;Kelly
Rich O&#39;Kelly

Reputation: 41757

This will do the trick:

$(function() {
  var dates = $('.dates');
  var html = dates.html(); 
  html = html.replace(/ (pm) /gi, ' $1 <br /> ');
  dates.html(html);
});

jsfiddle here

The above code will match all elements with a 'dates' class, and insert a break element after each ' pm ' that it finds, whilst respecting the casing of the original pm text.

Upvotes: 0

Xyan Ewing
Xyan Ewing

Reputation: 912

$('.dates').html($('.dates').html().replace('pm', 'pm<br />'));

http://jsfiddle.net/jLcKa/

Upvotes: 0

amit_g
amit_g

Reputation: 31250

Demo

$(function(){
    var dates = $(".dates").html();
    var regex = /([ap]m) /gi;

    dates = dates.replace(regex, "$1<br>");

    $(".dates").html(dates);
})

Upvotes: 0

bobek
bobek

Reputation: 8020

Here is an example. Just instead of removing the : add pm.

Replace text in string within an element after a specific character?

Upvotes: 0

szeliga
szeliga

Reputation: 621

you can use regular expressions sometihng like

var replaced = $("div.dates").html();
replaced = replaced.replace(/pm/gi, "pm <br />")
$("div.dates").html(replaced);

Upvotes: 1

SteveLacy
SteveLacy

Reputation: 4162

$('.dates').append($('<br />'));

Would that work?

Upvotes: 0

Related Questions