compunerd3
compunerd3

Reputation: 61

jQuery - Change multiple words into multiple images

I have a div with some platforms written there, I want to have jQuery replace each word with a matching image. Android would become an android icon, PS4 would be come a PS4 icon etc.

The HTML is not a list and the multiple text strings are inside one div.

$(".field-content").each(function() {
  if ($(this).children().length == 0) {
    var newHTML = $(this).html().replace('Firefox', '<img class="markdown-img" src="index.php?/attachments/get/6049" alt="" width="40">');
    $(this).html(newHTML);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="field-content">Xbox , Android, Chrome, Firefox</div>

What's happening is, if the jQuery runs, it replaces the entire div with an image and does not find multiple words / images to replace.

Any idea how I can run it to replace Xbox with an icon and if PS4 also exists, replace PS4 with an icon?

Upvotes: 1

Views: 58

Answers (1)

mplungjan
mplungjan

Reputation: 177684

You mean something like this? There is no HTML in the children of the div. It is a text string

var imgs = {
    "Xbox": "https://findicons.com/files/icons/382/console/128/xbox_360_zoomed_icon.png",
    "Android": "http://i.istockimg.com/file_thumbview_approve/25435190/3/stock-photo-25435190-green-android-with-shoping-bag.jpg",
    "Chrome": "chrome.gif",
    "Firefox": "firefox.gif",
    "PS4": "ps4.gif"
  }
$(".field-content").each(function() {
  var newHTML = [];
  $.each(
    $(this).text().split(","), // you were for sure missing this
    function(_, val) {
      val = $.trim(val);
      if (val.length > 0) {
        newHTML.push(val + ': <img class="markdown-img" src="' + imgs[val] + '" alt="Image of '+val+'">');
      }
    }
  );
  //    console.log(newHTML)
  if (newHTML.length > 0) $(this).html(newHTML.join("&nbsp"));
})
.markdown-img { width:40px }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="field-content">Xbox , Android, Chrome, Firefox</div>
<div class="field-content">Android, Chrome, PS4</div>

Upvotes: 2

Related Questions