Purplefish32
Purplefish32

Reputation: 647

Wrap a span around some text in 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

Upvotes: 5

Views: 6774

Answers (3)

David Thomas
David Thomas

Reputation: 253318

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.

Upvotes: 6

Raynos
Raynos

Reputation: 169401

var ul = document.getElementById("myId");
var li = ul.firstElementChild;
var text = li.firstChild;
var ul = li.childNodes[1];
ul.classList.add('myClass');
var span = document.createElement("span");
span.textContent = text.data;
li.replaceChild(span, text);

Old fashioned DOM to the rescue.

Upvotes: 3

RightSaidFred
RightSaidFred

Reputation: 11327

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

JSFIDDLE DEMO

Upvotes: 6

Related Questions