peehskcalba peehskcalba - 2 months ago 10
jQuery Question

How to use jQuery to convert text to email links

I have an HTML table with one column being email addresses; spambot issues aside, I'd like to convert each

<td>
element in this column to a mailto: link.

Here's what I've got:

$("table.data tbody tr td:last").each(function() {
var email = $(this).val();
$(this).html('<a href="mailto:' + email + '">' + email + '</a>');
});


And this is the table (sample):

<tr>
<td>Joe</td>
<td>Shmoe</td>
<td>example@example.net</td>
</tr>


What's going wrong?

Answer

Your jquery selector is wrong.

When you do 'table.data tbody tr td:last' it will only select the last cell of the last row.

What you need to do is something like:

$(document).ready(
    function()
    {
        //For each row...
        $('table.data tbody tr').each(
            function()
            {  
                //...find the last cell.
                var lastCell = $(this).find('td:last');
                $(lastCell).html('<a href="mailto:' + $(lastCell).text() + '">' + $(lastCell).text() + '</a>');
            }
        );
    }
);

Working demo: http://jsbin.com/umiza Code: http://jsbin.com/umiza/edit

Comments