如何使用jQuery在元素的内部文本的最后一个单词周围包裹一个范围?

时间:2011-02-09 21:18:39

标签: jquery html text

我知道这应该是一个简单的任务,但是我在选择标题元素的最后一个单词并将其包装在一个范围内时遇到了问题,因此我可以添加样式更改。

这是我到目前为止所拥有的

$('.side-c h3').split(/\s+/).pop().wrap('<span />');

非常感谢任何帮助

3 个答案:

答案 0 :(得分:15)

问题是jQuery对象包装了DOM节点。元素中的每个单词本身都不是DOM节点,因此您需要更多的工作来分解文本并重新加入它。您还需要考虑jQuery选择的多个节点。试试这个:

$('.side-c h3').each(function(index, element) {
    var heading = $(element), word_array, last_word, first_part;

    word_array = heading.html().split(/\s+/); // split on spaces
    last_word = word_array.pop();             // pop the last word
    first_part = word_array.join(' ');        // rejoin the first words together

    heading.html([first_part, ' <span>', last_word, '</span>'].join(''));
});

答案 1 :(得分:2)

这样做:

$('.side-c h3').each(function(){
   var $this = $(this), text=$this.text().trim(), words = text.split(/\s+/);
   var lastWord = words.pop();
   words.push('<span>' + lastWord + '</span>');
   $this.html(words.join(' '));
});

答案 2 :(得分:0)

嗯,这不是特别容易。最正统的方法是使用DOMNode.splitText

$('.side-c h3').each(function(){
    var oldNode = this.firstChild,
        newNode = oldNode.splitText(oldNode.data.lastIndexOf(' ') + 1), // don't wrap the space
        span = document.createElement('span');

    this.replaceChild(span, newNode);
    span.appendChild(newNode);
});

See jsfiddle

相关问题