0

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.

Simon Darby
  • 643
  • 5
  • 6

4 Answers4

2

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:me@me.com?subject=">Email Link</a></div>
biko
  • 510
  • 6
  • 15
1
$('#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());
});
Anubhav
  • 7,138
  • 5
  • 21
  • 33
  • 1
    Note that this will not work if you have more than one h1 tag on the page, and note that having multiple h1's on a page is HTML5 compliant. – biko Nov 26 '14 at 08:14
  • Thanks Biko. I have used an ID with the h1 to avoid any problems. – Simon Darby Nov 26 '14 at 08:36
1

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://
    });
Umair Hamid
  • 3,509
  • 3
  • 23
  • 25
0
$(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

Veve
  • 6,643
  • 5
  • 39
  • 58
Madhuka Dilhan
  • 1,396
  • 1
  • 14
  • 21