Search code examples
javascriptjqueryhtmlhreftextnode

Make selected text a variable & insert it


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)?


Solution

  • 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>