Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap HTML around a text node with jQuery?

Tags:

jquery

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

like image 747
Mary Daisy Sanchez Avatar asked Dec 01 '22 00:12

Mary Daisy Sanchez


2 Answers

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

like image 145
Joseph Avatar answered Dec 09 '22 20:12

Joseph


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}
like image 42
amd Avatar answered Dec 09 '22 20:12

amd