I have the following markup:
<div class="print">
<p><a href="/">Printable Format</a></p>
</div>
However, I want to wrap "Printable Format" within a :
<div class="print">
<p><a href="/"><span>Printable Format</span></a></p>
</div>
I have looked at several examples, but they don't seem to accomplish what I'm looking for.
Thank you in advance!
Use .contents() with .wrap()
//
$('.print').find('a').contents().wrap('<span/>')
// same as $('.print a').contents().wrap('<span/>')
or wrapInner() - which does the same thing
$('.print').find('a').wrapInner('<span/>')
// same as $('.print a').wrapInner('<span/>')
Pure JS example for @Alfo
// returns an array of elements
var dtag = document.getElementsByClassName('print');
// gets first anchor tag inside first class=print
var atag = dtag[0].getElementsByTagName('a')[0];
// add span tag
atag.innerHTML = '<span>' + atag.innerHTML+ '</span>';
If you want to do multiple elements, you will have to loop through the arrays
$('.print a').html(function(i, h){
return '<span>' + h + '</span>';
});
Assuming you want to do this with jQuery:
var $span = $( "<span></span>" ), // Create element
$link = $( '.print > p > a' );
$span.text( $link.text() );
$link.html( $span );
$('.print a').wrapInner('<span/>');
Will produce:
<a href="/"><span>Printable Format</span></a>
Here is the jQuery reference: http://api.jquery.com/wrapInner/
Here is my Fiddle: http://jsfiddle.net/tracyfu/bHVtg/
With Pure Javascript you can try this
var elem = document.getElementsByClassName('print')[0]
.getElementsByTagName('a')[0] ;
var html = elem.innerHTML;
elem.innerHTML = '<span class="red">'+ html + '</span>' ;
Set the break-word property to the span.
Example HTML:
<span class="wrapped-link"><a href="#">my link</a>
Example CSS
.wrapped-link{
word-break: break-word;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.