开发者

jQuery enclose text before and after anchor tag in separate spans

I have this code:

<p>Hi. I am your friend. you are my friend.<br> we <a href="both.html">both&开发者_开发百科lt;/a> are friends.</p>

My aim is to enclose the text before the anchor tag as well as after the anchor tag into separate spans. Thus, i want something like this in the DOM:

<p><span>Hi. I am your friend. you are my friend.<br> we </span><a href="both.html">both</a><span> are friends.</span></p>

Can anybody please help me and tell me how to do it in jQuery?


From this answer, you should be able to do something like the following:

$("p").contents().filter(function() {
    return this.nodeType == Node.TEXT_NODE;
}).wrap("<span/>");


The issue is that the content before or after your <a> may have other DOM nodes, so they wont end up being simply TEXT_NODEs. This is a lot longer of an implementation, but it achieves exactly the result your question stated. You can view a demo on JSFiddle.

$.fn.wrapSides = function () {
    return this.each( function (index, el) {
       var $parent = $(el).parent(),
           contents = $.makeArray($parent.contents()),
           before, after, i, matched, build = $();

        for (i = 0; i < contents.length; i++) {
            if( contents[i] === el) {
                before = contents.slice(0, i);
                after = contents.slice( Math.min(contents.length - 1, i + 1), contents.length);
                matched = contents.slice(i,i + 1);
                break;   
            }
        };

        if (before && before.length) {
            build = build.add($("<span>").append(before));
        }

        build = build.add(matched);

        if (after && after.length) {
            build = build.add($("<span>").append(after));
        }

        $parent.html( build );
    }); 
};

You just call it on the tag you want to act as the splitter, so in your case it would be the a:

$("p a").wrapSides();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜