Myles Malloy Myles Malloy - 4 months ago 5x
jQuery Question

Conditional statement for replacing text inside of an element with jQuery

There is text generated inside of some span elements in which I would like to replace if the right conditions are met. The text I want swapped out is either "am" (with the intention to switch to a.m.) or "pm" (to p.m.), and the condition is essentially "if this span contains part of a string with 'am' or 'pm', replace that part of the string with 'a.m.' or 'p.m.'.

My html/php looks something like this...

<span id="start-time">
~Drupal Jargon which essentially outputs something like:~
5 pm

I was able to swap out the pm in this example with text().replace...

$("#start-time").each(function() {
$am = $(this).text().replace('pm','p.m.');

... but the conditional statement I created (seen below) removes the "5 " from the text string inside of the start-time span so it just outputs "p.m.", not the desired "5 p.m.".

$("#start-time").each(function() {
if ($("#start-time").text("pm")) {
$pm = $(this).text().replace('pm','p.m.');

How can I fix my code so the conditional statement outputs the desired text?


Since you are using "each" (check the docs, you should use callback parameters. Not

$(".start-time").each(function() {
  if ($("#start-time")..


$(".start-time").each(function(i,e) {
  if ($(e)..

Demo here