Reputation: 253
I have some HTML construct like the following:
<div class="info_contact">
<h2>Contact</h2>
<p><strong>E-Mail</strong><a href="mailto:[email protected]">[email protected]</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)?
Upvotes: 0
Views: 72
Reputation: 18908
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:[email protected]">[email protected]</a>
</p>
<p><strong>Tel.</strong>+44 2456-458</p>
<p><strong>Fax </strong>0123 456 7879</p>
</div>
Upvotes: 0
Reputation: 207537
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:[email protected]">[email protected]</a></p>
<p><strong>Tel.</strong>+44 2456-458</p>
<p><strong>Fax </strong>0123 456 7879</p>
</div>
Upvotes: 1