2016-05-31 85 views
2

孩子,我有一些HTML這樣的:div如何替換父元素的內容,而忽略使用jQuery

<div id="demo"> 
    <p> 
     <span class="myClass">Word test should not be marked</span> 
     Word test should be marked<br /> 
    </p> 
</div> 

我怎樣才能找到一個詞(「測試」),不包括span並用它標記jQuery的?在我看到很多解決方案等,但他們都沒有爲我工作。僅供參考我想使用的代碼是這樣的:

var regex = XRegExp('test', 'i'); 
$('#demo').markRegExp(regex); 
+0

我不知道我理解你。你想通過在'.myClass'範圍內用'span'包裝來突出顯示'test'這個詞嗎? –

回答

1

使用contents()獲取所有子節點,然後遍歷和更新文本節點。

$('#demo p') 
 
    .contents() // get all child nodes including text and comment nodes 
 
    .each(function() { // iterate over nodes 
 
    if (this.nodeType == 3) // check node is text node 
 
     $(this).replaceWith(this.textContent.replace(/test/g, '<span class="test">$&</span>')) // update the content and replace node with html content 
 
    });
.test { 
 
    color: red; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div id="demo"> 
 
    <p> 
 
    <span class="myClass">Word test should not be marked</span> 
 
    Word test should be marked 
 
    <br /> 
 
    </p> 
 
</div>

+0

請檢查我剛剛添加到您的代碼的修復程序是您的意圖,我認爲它是,否則它失敗 –

+1

不起作用。 '應該標記單詞測試'仍然是'p'的根。 – Mohammad

+0

@DarrenSweeney:謝謝:) –

0

這裏是一個繁瑣的正則表達式的解決方案:

var html=$("#demo").html(); 
    var elements=html.split(/(<[^>]+>)/); // split into tags and text 
    $.each(elements,function(i,e){ 
    if(!e.match(/<[^>]+>/)){ 
     if(elements[i-1]!==undefined){ 
     if(!$(elements[i-1]).hasClass('myClass')){ 
      elements[i]=elements[i].replace(/test/g,"<span class='highlight'>test</span>"); 
     } 
     } 
    } 
    }); 
    $("#demo").html(elements.join('')); 

這將是乾淨多了,不過,標記文本,你想用一個類來代替,然後你可以這樣做:

$("#demo").find("span[class='myClass']").each(function(){ 
    $(this).html($(this).text().replace(/test/g,"<span class='highlight'>test</span>")); 
}); 

工作JSFiddle兩種解決方案。