Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrap a span around some text in jQuery

Tags:

jquery

What I have :

<ul id="myId">
    <li>
        My text
        <ul class="myClass">
            <li>blahblahblah</li>
        </ul>
    </li>
</ul>

What I want :

<ul id="myId">
    <li>
        <span>My text</span>
        <ul class="myClass">
            <li>blahblahblah</li>
        </ul>
    </li>
</ul>

I dont have access to the HTML markup, and am wanting to do this with jQuery, Something like :

$('.myClass').get_the_text_ubove().wrap('<span>');

There must be some way of selecting 'My text' even though it has no class/id

like image 345
Purplefish32 Avatar asked Dec 09 '11 16:12

Purplefish32


2 Answers

Try:

$('#myId > li').each(
    function(){
        $(this.firstChild).wrap('<span></span>');
    });

JS Fiddle demo.

With regards to wanting to add the class to the ul:

$('#myId > li').each(
    function(){
        $(this.firstChild).wrap('<span></span>');
        $(this).find('ul').addClass('myClass');
    });

JS Fiddle demo.

like image 191
David Thomas Avatar answered Nov 12 '22 02:11

David Thomas


$($('#myId ul').addClass('myClass')[0].previousSibling).wrap('<span>');

JSFIDDLE DEMO

like image 6
RightSaidFred Avatar answered Nov 12 '22 02:11

RightSaidFred