Surrounding individual words inside HTML text with SPAN tags?

前端 未结 3 1873
不思量自难忘°
不思量自难忘° 2020-12-20 01:48

I need to surround individual words inside an HTML element with SPAN tags. So something like this:

Foo bar baz

        
相关标签:
3条回答
  • 2020-12-20 02:20

    You can inspect the source of this jQuery plugin to see how they do this, then extract the functionality you need.

    0 讨论(0)
  • 2020-12-20 02:22

    try using .wrap() jQuery method

    0 讨论(0)
  • 2020-12-20 02:42

    To do this you will need to walk the DOM and understand how to process the individual nodes.

    The basic walk code is this:

    function walk(root)
    {
        if (root.nodeType == 3) // text node
        {
            doReplace(root);
            return;
        }
        var children = root.childNodes;
        for (var i = children.length - 1 ; i >= 0 ; i--)
        {
            walk(children[i]);
        }
    }
    

    The walk function checks all the children of the input node and:

    • if it sees a text node it calls the replacement function
    • otherwise it recursively calls itself with the child node as the new input node.

    Note that because the code in-place replaces nodes, the "children" node list will be affected by the replacement. To avoid this affecting the algorithm, the children are visited in reverse order.

    The doReplace function is like this:

    function doReplace(text)
    {
        var div = document.createElement("div");
        div.innerHTML = text.nodeValue.replace(/\b(\w+)\b/g, "<span>$1</span>");
        var parent = text.parentNode;
        var children = div.childNodes;
        for (var i = children.length - 1 ; i >= 0 ; i--)
        {
            parent.insertBefore(children[i], text.nextSibling);
        }
        parent.removeChild(text);
    }
    

    This creates a container node, then applies the regex and uses innerHTML to parse the result into a DOM fragment. The children of the div element can then replace the text node in the document. Again the moving of the nodes is done in reverse order so that the mutation of the source node list doesn't affect the loop.

    Finally, the change can be applied by calling the walk function.

    e.g.

    window.onload = function() { walk(document.body); };
    

    A complete working example can be found at http://www.alohci.net/text/html/wordwrapper.htm.ashx

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