0

I'm trying to replace specific text within a link with Font Awesome Icons. I am able to do that, but the icons are all the same(as first one). Why is it showing duplicates and how do I fix it?

HTML:

<ul>
  <li><a href="http://">FacebookIcon</a></li>
  <li><a href="http://">FacebookIconCircle</a></li>
  <li><a href="http://">FacebookIconSquare</a></li>
</ul>

jQuery:

$('#main-header .widget.Header .header-widget .header-identity .header-title-tagline ul li a:contains("FacebookIcon")').html('<i class="fab fa-facebook-f"></i>');
$('#main-header .widget.Header .header-widget .header-identity .header-title-tagline ul li a:contains("FacebookIconCircle")').html('<i class="fab fa-facebook"></i>');
$('#main-header .widget.Header .header-widget .header-identity .header-title-tagline ul li a:contains("FacebookIconSquare")').html('<i class="fab fa-facebook-square"></i>');

Result:

<ul>
  <li><a href="http://"><i class="fab fa-facebook-f"></i></a></li>
  <li><a href="http://"><i class="fab fa-facebook-f"></i></a></li>
  <li><a href="http://"><i class="fab fa-facebook-f"></i></a></li>
</ul>

Desired Result

<ul>
  <li><a href="http://"><i class="fab fa-facebook-f"></i></a></li>
  <li><a href="http://"><i class="fab fa-facebook"></i></a></li>
  <li><a href="http://"><i class="fab fa-facebook-square"></i></a></li>
</ul>
Xarcell
  • 2,011
  • 6
  • 33
  • 65
  • Every one of them contains `FacebookIcon`. Therefore at the first HTML replacement, every one of them is replaced with icons. Maybe you should check for equality rather than containment. – Harun Yilmaz Jul 11 '20 at 12:07
  • Yes, the solution here works: https://stackoverflow.com/questions/15364298/select-element-by-exact-match-of-its-content – Xarcell Jul 11 '20 at 12:14

1 Answers1

2

While you might consider using .filter() to further specify your selector, it might be better to consider using .html(). Using .html(), you can iterate through all your selected <a> elements. You can also make an object which maps icons names to font-awesome tags. For each anchor tag, you can get its text, and use that in the look-up for the object like so:

const icons = {
  'FacebookIcon': '<i class="fab fa-facebook-f"></i>',
  'FacebookIconCircle': '<i class="fab fa-facebook"></i>',
  'FacebookIconSquare': '<i class="fab fa-facebook-square"></i>'
};

$('a').html(function() {
  return icons[$(this).text()];
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css">
<ul>
  <li><a href="http://">FacebookIcon</a></li>
  <li><a href="http://">FacebookIconCircle</a></li>
  <li><a href="http://">FacebookIconSquare</a></li>
</ul>
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
  • Use this URL in your example to get the icons to appear: https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css – Xarcell Jul 11 '20 at 12:20