First word selector

后端 未结 7 711
野性不改
野性不改 2020-11-29 06:04

How can I select the first word in a div?

I need to be able to insert a line break after the first word, or wrap it in a span tag. I need to do this for multiple di

7条回答
  •  半阙折子戏
    2020-11-29 06:46

    Actually, if you want to use it as a plugin, so that it would do it for all the items in the selector, not only the first one, use this one:

    $.fn.wrapStart = function(numWords){
        return this.each(function(){
            $this = $(this);
            var node = $this.contents().filter(function(){
                return this.nodeType == 3
            }).first(),
            text = node.text(),
            first = text.split(" ", numWords).join(" ");
            if (!node.length) return;
            node[0].nodeValue = text.slice(first.length);
            node.before('' + first + '');
        });
    };
    

    http://jsfiddle.net/rxAMF/

提交回复
热议问题