How to wrap each word of an element in a span tag?

前端 未结 8 1778
忘掉有多难
忘掉有多难 2020-12-01 07:05
$(\"div.date\")
    .contents()
    .filter(
        function(){
            return this.nodeType != 1; 
        })
    .wrap(\"\");

I

8条回答
  •  粉色の甜心
    2020-12-01 07:36

    If your element contents contains child elements (HTML) then the above solutions are not useful.

    Here's a jsfiddle I've come up with that preserves HTML (elements and their attributes). The shortcoming of this small snippet is that if you have events binded to the element's contents then they will be lost since innerHTML is being reassigned to something else.

    This code does not require any special libraries (like jQuery).

    https://jsfiddle.net/4b5j0wjo/3/

    var e = document.getElementById('words');
    e.innerHTML = e.innerHTML.replace(/(^|<\/?[^>]+>|\s+)([^\s<]+)/g, '$1$2');
    

提交回复
热议问题