Timothy Grees
Timothy Grees

Reputation: 121

Add mailto: with jQuery?

<table id="here" border="1">
    <tr><td>London</td><td>[email protected]</td><td>aaa</td><td>aaa</td></tr>
    <tr><td>Manchester</td><td>[email protected]</td><td>aaa</td><td>aaa</td></tr>
    <tr><td>Liverpool</td><td>[email protected]</td><td>aaa</td><td>aaa</td></tr>
    <tr><td>Ipswich</td><td>[email protected]</td><td>aaa</td><td>aaa</td></tr>
</table>

Is possible add link mailto: for second columns with email addresses with jQuery (not modify HTML)? If yes, how?

http://jsfiddle.net/zwsMD/1/

Upvotes: 2

Views: 5630

Answers (4)

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76880

You could do something like this

​$('td:nth-child(2)').each(function(){
   var text = $(this).text();
    var href = "mailto:"+text;
    var $a = $('<a>', { href: href, text: text});
    $(this).text('').append($a);
});​​​​​​​​​​​​​​​​​​​​

fiddle here http://jsfiddle.net/zwsMD/6/

Upvotes: 2

Alex Turpin
Alex Turpin

Reputation: 47776

You will need to loop around every row, find the cell you want and wrap a link around the content. You can use wrapInner for this.

$("#here tr").each(function() {
    var td = $(this).children().eq(1);
    var email = "mailto:" + td.text();
    td.wrapInner($("<a>").prop("href", email));
});​

Live example

Upvotes: 2

pimvdb
pimvdb

Reputation: 154838

You could just replace the contents of each second td with an a element with a mailto: href: http://jsfiddle.net/zwsMD/5/.

​$("#here td:nth-child(2)").each(function() {
    var email = $(this).text();

    // replace contents
    $(this).html(
        $("<a>").attr("href", "mailto:" + email).text(email)
    );
});​​​​​​​​​​​​​​​​​​​​

Upvotes: 5

James Allardice
James Allardice

Reputation: 165971

Assuming it's always the second td of each row, you could iterate over those elements and wrap the contents in an a element:

$("#here td:nth-child(2)").each(function() {
    $(this).contents().wrap("<a href='mailto:" + $(this).text() + "'>");
});​

Here's a working example.

Upvotes: 2

Related Questions