Myles Malloy Myles Malloy - 5 months ago 7
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
</span>


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.');
$(this).text($am);
});


... 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.');
$(this).text($pm);
}
});


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

Answer

Since you are using "each" (check the docs, http://api.jquery.com/jquery.each/) you should use callback parameters. Not

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

but

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

Demo here https://jsfiddle.net/uet5LbLb/