Wrap a span around some text in jQuery

后端 未结 3 778
孤城傲影
孤城傲影 2021-01-18 18:45

What I have :

  • My text
    • blahblahblah
相关标签:
3条回答
  • 2021-01-18 19:24

    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.

    0 讨论(0)
  • 2021-01-18 19:24
    $($('#myId ul').addClass('myClass')[0].previousSibling).wrap('<span>');
    

    JSFIDDLE DEMO

    0 讨论(0)
  • 2021-01-18 19:33
    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.

    0 讨论(0)
提交回复
热议问题