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

921 Views Asked by At

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:[email protected]?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.

4

There are 4 best solutions below

2
On BEST ANSWER
$('#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());
});
1
On

Here you go. Assuming your HTML structure stays the same, first, we select #mailme as the ancestor of the link using the .closest function. Then, we select the previous sibling of #mailme using the .prev function. Check out the working code snippet.

var headline;
$('#mailme a').each(function() {
  headline = $(this).closest('#mailme').prev('h1').text();
 $(this).attr('href', $(this).attr('href') + headline);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h1>Headline</h1>
<div id="mailme"><a href="mailto:[email protected]?subject=">Email Link</a></div>

0
On

Use this whole code.

    $(document).ready(function(){
       var mailtoHref = $('#mailme a').attr('href'); //get href
       var h1Text = $('h1').text(); //get h1 text
       $('#mailme a').attr('href', mailtoHref + h1Text ); //append it to mailto://
    });
0
On
$(function() {
  $('#copy').append($('.elem').clone().children('a').prepend('foo - ').parent().clone());
});

Use this type of method, follow this link : http://bugs.jquery.com/query?milestone=1.5&group=status&page=4&order=version&row=description