How to wrap HTML around a text node with jQuery?

Go To StackoverFlow.com

2

<div class="pagination">
  <a href="#">1</a>
  <a href="#">2</a>
  3
  <a href="#">4</a>
</div>

I need to use jQuery to wrap an HTML element around the number "3". I can't modify the HTML because it is dynamically generated.

2012-04-04 06:14
by Mary Daisy Sanchez
I think that will be useful: http://stackoverflow.com/questions/8568657/wrap-stray-text-in-div - devnull69 2012-04-04 06:18
thanks for this lin - Mary Daisy Sanchez 2012-04-09 00:29


5

this will wrap all your number with a span, so the structure will be :

<a><span>1</span></a>

and the selected one only span without a :

<span>2</span>


var html = $('.pagination').html();
    html = html.replace(/[0-9]/g,"<span>$&</span>");
    $('.pagination').html(html);

so you can easily style it with :

.pagination a span {normal style} 
.pagination span{selected style}
2012-04-04 07:02
by amd
your awesome dud - Mary Daisy Sanchez 2012-04-08 23:55
then accept his answer - 11684 2012-04-09 07:12
@user560756 or you won't be notified - 11684 2012-04-09 07:14
why not simply $('.pagination').html('<span>'+$('.pagination').html()+'</span>');Imran Bughio 2016-02-05 12:11


11

I had a similar question which wraps all stray text

$(function() {

    var test = $('.pagination')
        .contents()
        .filter(function() {
            return this.nodeType === 3 && $.trim(this.nodeValue) !== '';
        })
        .wrap('<span/>');

});​

just had a minor confusion with wrap() and wrapAll(). here's a demo

2012-04-04 06:30
by Joseph
not working...... - Royi Namir 2012-04-04 06:37
it changed the order of the elements http://jsbin.com/uvigam/edit#javascript,htm - Royi Namir 2012-04-04 06:39
it's now updated. this time, i have a demo. i got confused with wrap() and wrapAll() - Joseph 2012-04-04 06:41
+1 good work..... - Royi Namir 2012-04-04 06:43
This solution worked just fine for me. Thanks - Ricardo Zea 2012-10-20 03:03


1

This is old, but a shorter, simpler way to do this in my opinion would be:

$("div:not(a)").wrapInner("<a href='#'></a>");
2015-05-13 15:45
by 1252748
Ads