Search code examples
jqueryclonehrefmailto

How to copy/clone HTML headline text to href mailto subject line with jquery?


I want to grab the h1 headline text and add it to the subject line of mailto. I got as far as this. I just don't know how to substitute 'replace this with the headline' with the correct expression. Would clone be in the right direction? Thanks for taking a look!

<h1>Headline</h1>
<div id="mailme"><a href="mailto:me@me.com?subject=">Email Link</a></div>


$('#mailme a').each(function() {
$(this).attr('href', $(this).attr('href') + 'replace this with the h1 headline');
});

Thanks to everyone that pitched in solutions. I have used it in a simple HTML page template where the client is editing content but has no HTML skill. Each content page has a email button which uses one of the scripts below to customize the email subject line depending on the page headline. I hope others will find this useful too.


Solution

  • $('#mailme a').each(function() {
        $(this).attr('href', $(this).attr('href') + $('h1').text());
    });
    

    This should work.

    If you have multiple h1 tags (as pointed out by biko) the following will work

    $('#mailme a').each(function() {
        $(this).attr('href', $(this).attr('href') + $(this).closest('#mailme').prev('h1').text());
    });