0

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?

1 Answer 1

1

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/

Sign up to request clarification or add additional context in comments.

4 Comments

That works to remove the facebook anchor text. How do I take facebook anchor text, convert it to a class on the icon element. So facebook becomes a class of fa-facebook on the second icon element
What would you like the class to be ? just facebook? And on the span I guess right?
fa-facebook on the <i class="fa fa-stack-1x fa-inverse">. However if the anchor text is twitter it would have to be fa-twitter etc.
Works great. Just never even thought to use a variable. Thanks alot. I had been stuck on this for about an hour. I will mark as answered. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.