2014-03-03 32 views
0

我使用下面的腳本找到所有H1元素,父ID容器,將適合帷幕標準之內...的jQuery找到準確的HTML內容

$('#cpcompheader h1').html(" ").remove(); 

該腳本找到任何情況下,如....

<h1>&nbsp;</h1> 
<h1>&nbsp; one two</h1> 
<h1>&nbsp; the sun is up</h1> 
<h1>&nbsp; etc...</h1> 

但我只是想找到的所有實例...

<h1>&nbsp;</h1> 

那麼我們應該如何修改我的代碼?謝謝!

回答

1

你可以嘗試找到所有的h1標籤,然後檢查它們是否包含某個值。

$('#yourParent h1').each(function(){ 
    if($(this).html() == "&nbsp;"){ 
     // magic 
    } 
}); 
+0

爲什麼不在選擇器中包含if檢查?此外,當' '不是唯一的內容時,您的字符串將不匹配。你可能需要一個正則表達式。 – isherwood

+1

我想你可以在選擇器中包含'if'語句。關於內容,我想他只是想抓住那些只匹配一個' ' – Coderchu

0

我想你可以這樣做:

$('h1:contains(&nbsp;)'); 

,或者如果你想要的精確匹配:

$('h1').filter(function(index) { return $(this).text() === "&nbsp;"; }); 

你也可以看看包含選擇文檔:https://api.jquery.com/contains-selector/

+0

這將不匹配只包含指定的值,雖然,它包括任何H1的有 元素。這取決於OP想要的。 – Coderchu

+0

'包含()'查找HTML實體嗎? – isherwood

+0

@isherwood我不這麼認爲。我已編輯的答案添加確切的字符串匹配:) –

2

如果你想刪除包含NBSP所有H1S你可以嘗試這樣的事: removing all elements that contains nbsp

$("h1").each(function() { 
if ($(this).html().indexOf("&nbsp;") != -1) { 
    $(this).remove(); 
} 
}); 

現在,如果你想刪除元素完全匹配的NBSP只是修改成這樣的:modified version

$("h1").each(function() { 
    if ($(this).html() === "&nbsp;") { 
     $(this).remove(); 
    } 
}); 
0
var myRegEx = new RegExp('^&nbsp;\s');  

$('#myDiv h1').each(function() { 
    var myText = $(this).text(); 

    if (myText.match(myRegEx)) { ... } 
}); 
0

你可以過濾器使用正則表達式的元素,然後將其刪除,如果不具有任何價值

$('h1').each(function(){ 
    var filtered = $(this).html($(this).html().replace(/&nbsp;/gi,''));  
    if($(filtered).html() === ''){ 
    $(filtered).remove(); 
    } 
}); 

here a demo