0

I have some HTML construct like the following:

<div class="info_contact">
    <h2>Contact</h2>
    <p><strong>E-Mail</strong><a href="mailto:someone@address.com">someone@address.com</a></p>
    <p><strong>Tel.</strong>+44 2456-458</p>
    <p><strong>Fax </strong>0123 456 7879</p>
</div>

The aim is to make the telephone number clickable via jQuery/Javascript. So far I managed to select and wrap the text in an a tag as needed:

jQuery(document).ready(function(jQuery) {
    jQuery( '.info_contact p:contains("Tel.")' )
    .contents()
    .filter(function(){
        return this.nodeType == 3;
    })
    .wrap( '<a href="tel:"></a>' );
});

But unfortunately that lacks the option to insert the selected text as the href, so the corresponding line become this:

<p><strong>Tel.</strong><a href="tel:+44 2456-458">+44 2456-458</a></p>

Is there a way to insert the selected text into the href attribute, possibly through creating a variable (or an alternative)?

physalis
  • 253
  • 4
  • 16

2 Answers2

1

wrap supports using a function

jQuery(document).ready(function(jQuery) {
    jQuery( '.info_contact p:contains("Tel.")' )
    .contents()
    .filter(function(){
        return this.nodeType == 3;
    })
    .wrap( function(){ return '<a href="tel:' + $(this).text() + '"></a>' });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="info_contact">
    <h2>Contact</h2>
    <p><strong>E-Mail</strong><a href="mailto:someone@address.com">someone@address.com</a></p>
    <p><strong>Tel.</strong>+44 2456-458</p>
    <p><strong>Fax </strong>0123 456 7879</p>
</div>
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • Nice and easy, this is the smoothest solution I could think of. Thanks for pointing out a way to actually use .wrap and just add a function to it! Perfect! – physalis Jul 23 '16 at 13:02
0

You could loop (each) the results after the filter, and wrap inside of that instead:

jQuery(document).ready(function(jQuery) {
  jQuery('.info_contact p:contains("Tel.")')
    .contents()
    .filter(function() {
      return this.nodeType == 3;
    })
    .each(function(i, data) {
      $(data).wrap('<a href="tel:' + data.wholeText + '"></a>');
    })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="info_contact">
  <h2>Contact</h2>
  <p><strong>E-Mail</strong><a href="mailto:someone@address.com">someone@address.com</a>
  </p>
  <p><strong>Tel.</strong>+44 2456-458</p>
  <p><strong>Fax </strong>0123 456 7879</p>
</div>
KevBot
  • 17,900
  • 5
  • 50
  • 68