是否可以在父元素中找到文本并将其包装?

时间:2014-01-15 10:27:31

标签: javascript jquery

我有一段看起来像这样的代码:

<div class="breadcrumbs">
    <a href="#">Root element</a>
    <a href="#">Blog</a>
    Page 2
</div>

我想要做什么,我不确定是否可以通过使用jQuery将上述代码段转换为以下内容:

<div class="breadcrumbs">
    <a href="#">Root element</a>
    <a href="#">Blog</a>
    <span class="paginationSection">Page 2</span>
</div>

有没有办法用jQuery实现这个目标?

更新#1

这是我为了为我工作所做的代码。我在这里放置代码只是为了帮助其他人在这个功能中。

// Get the breadcrumb element
var t = document.getElementsByClassName('breadcrumbs');
// Assign the breadcrumb element into t variable
var t = t[0];
// Get the text of the last node in the breadcrumb element
var currentText = t.childNodes[t.childNodes.length - 1].nodeValue;

// If currentText it is not empty
if($.trim(currentText) != '')
{
    // Create a new span element
    var span = document.createElement('span');
    // Set the class I need
    span.className = 'pagination';
    // Set the text to currentText
    span.innerHTML = currentText;
    // Empty the last node value
    t.childNodes[t.childNodes.length - 1].nodeValue = '';
    // Append the span on .breadcrumb element.
    t.appendChild(span);
}

最后,我要感谢你们所有人参与这个问题:)

4 个答案:

答案 0 :(得分:2)

当然可以,以下假设文本'Page 2'将是.breadcrumbs内唯一的文本节点。检查节点值是否只是$.trim()的空格:

$('.breadcrumbs').contents().filter(function(){
    return this.nodeType === 3 && $.trim(this.nodeValue);
}).wrap('<span class="paginationSection"></span>');

JSFiddle

答案 1 :(得分:2)

试试这个:

$('.breadcrumbs').text().wrap('<span class="paginationSection" />');

<强>更新

试试这个:

fiddle

$('.breadcrumbs').text(function(index,text){return this.text}).wrap('<span class="paginationSection" />');

<强> UPDATE2:

这是解决实际问题作为问题要求的最佳方式:demo

$('.breadcrumbs').contents()
.filter(function(){
return this.nodeType !== 1;
}).wrap('<span class="paginationSection" />');

答案 2 :(得分:1)

使用

执行此操作的一种简单方法
document.getElementsByClassName('breadcrumbs')[0].innerHTML = 
          document.getElementsByClassName('breadcrumbs')[0]
          .innerHTML
          .replace('Page 2', '<span class="paginationSection">Page 2</span>')

JSFiddle


根据您的comments,我更新了

var ele = document.getElementsByClassName('breadcrumbs')[0];
var rege = /Page \d+/;
var matchy = ele.innerHTML.match(rege);
ele.innerHTML = ele.innerHTML.replace(matchy, '<span class="paginationSection">'+ matchy +'</span>')

JSFiddle

答案 3 :(得分:0)

是的可能

var t = $(".breadcrumbs")[0];
t.innerHTML = t.innerHTML.replace('Page 2', '<span class="paginationSection">Page 2</span>');
相关问题