0

I want to style a certain character in a string via jQuery, but have no clue how to approach that. I have the following situation

<a href="" accesskey="i">Link</a>

Now i want to underline the character in the accesskey (so the 'i' in this case) in the clickable link. So the 'i' in 'Link' should be underlined

Does anybody know how?

Maurice
  • 1,082
  • 1
  • 20
  • 43

4 Answers4

4

My own approach would be:

$('a[accesskey]').each( //selects only those a elements with an accesskey attribute
    function(){
        var aKey = $(this).attr('accesskey'); // finds the accesskey value of the current a
        var text = $(this).text(); // finds the text of the current a
        var newHTML = text.replace(aKey,'<span class="access">' + aKey + '</span>');
        // creates the new html having wrapped the accesskey character with a span
        $(this).html(newHTML); // sets the new html of the current link with the above newHTML variable
    });

JS Fiddle demo.

References:

David Thomas
  • 249,100
  • 51
  • 377
  • 410
1

I replaced the "i" with a span dynamically:

var jq = $('a');
var text = jq.text().replace(jq.attr('accessKey'), '<span style="text-decoration: underline;">i</span>');
jq.html(text);

http://jsfiddle.net/FishBasketGordo/QGEzA/

FishBasketGordo
  • 22,904
  • 4
  • 58
  • 91
  • This is a great answer, but what happens for something like "Invite"? It would replace the second "i" instead of the more logical first. Also, if you use "invite" instead, you get two styled "i"s. It might be best to just hard code the styling. @Maurice Why do you want to do this with jQuery? There might be another solution that doesn't involve jQuery... – Abishai Gray Jun 22 '11 at 17:56
  • 1
    @Abishai Gray If you want to replace the "I" in "Invite", then "I" should be the accessKey, not "i". Also, the `replace` function only replaces the first instance of the matched string unless a regex is passed in with the global flag, so only the first "i" in "invite" would be underlined. – FishBasketGordo Jun 22 '11 at 18:09
0

If it is just for this case, I would do it in the HTML rather than in JQuery:

<a href="" accesskey="i" style="text-decoration:none">L<u>i</u>nk</a>

Note: The "text-decoration:none" is needed to remove the default underline for links, though you should probably set this in CSS.

Here's a fiddle for that method.

If you still want to do it with JQuery, you can just change the link style and inner html to the above.

Briguy37
  • 8,342
  • 3
  • 33
  • 53
0

There's a plugin called "Highlight" which will highlight bits of text based on a search string. Plugin here.

For usage instructions, see this article. (I wrote for Smashing a while ago)

Jon Raasch
  • 3,703
  • 6
  • 30
  • 32