Reputation: 746
I am using a CMS which builds navigation with text based anchors only so its current output is
<li class="socialLinks"><a href="http://www.facebook.com">facebook</a></li>
I need to manipulate these links to work with font awesome. Essentially I want to remove the anchor text but at the same time using it to have a class appear on an icon element. The final list elements should look like this. So take the anchor text of "facebook" and adding it to the second icon element as a class of fa-facebook.
<li class="socialLinks"><a href="http://www.facebook.com"><span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-facebook fa-stack-1x fa-inverse"></i> </span></a></li>
I was attempting to use .prepend to find the .socialLinks a element and prepending the anchor text with jQuery like so. And this works, I just can't figure out how to now take the anchor text and convert it to fa-facebook and add it to the icon with class of .fa-stack-1x. And then remove the anchor text altogether.
$('.socialMediaLinks a').each(function() {
$(this).prepend('<span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-stack-1x fa-inverse"></i> </span>');
});
this returns
<li class="socialLinks"><a href="http://facebook.com" target="_blank"><span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-stack-1x fa-inverse"></i> </span>Facebook</a></li>
What is the best course of action. Secondly should I put this on document ready or something else?
Upvotes: 0
Views: 98
Reputation: 11353
You can make use of of this property of .html()) to replace html aware of the previous html in each element:
$('.socialMediaLinks a').html(function(i, html) {
var mediaclass = 'fa-' + $.trim(html).toLowerCase();
return '<span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-stack-1x ' + mediaclass + ' fa-inverse"></i> </span>';
});
Fiddle: http://jsfiddle.net/RBzwk/
Upvotes: 1