2011-12-17 60 views
1

我想獲取包含特定文本的元素。當我使用:contains選擇器時,結果也是該特定元素的所有父元素。使用jQuery中的特定文本搜索元素

此外,如果實際上包含文本的元素多於,則選擇器的結果非常麻煩。是否有可能只獲取包含特定文本的元素?

感謝, 喬爾

編輯:

例子:

<body> 
    <div> 
     <div> 
      <div>text</div> 
     </div> 
    </div> 
</body> 

和$( 「分區:包含( '文本')」)結果:

[<div>​…​</div>​, <div>​…​</div>​, <div>​text​</div>​] 

我想要一種方法只能得到<div>text</div>元素。 (我知道我可以使用.get(-1)來獲取最後一個元素,但是我想知道是否有更多的gemeric)。

+0

你可以發佈你的html以及你想獲得什麼元素與你不想獲得什麼元素的例子嗎? – mrtsherman 2011-12-17 06:37:29

+0

嗨,我不理解你,你是什麼意思關於「文本」?你的意思是InnerText?或InnerHTML? – 2011-12-17 06:38:27

回答

3

你可以嘗試這樣的:

$(":contains('text')").each(function() { 
    if($(this).find(":contains('text')").length > 0) { 
    // ignore. this is just an element containing at least 1 child containing 'text' 
    } 
    else { 
    // this is an element you want, directly contains 'text' 
    // .. your code here .. 
    } 
}); 
0

我不KHOW這樣工作的權利,但你選擇了它,如果它不能正常工作,發表評論我來編輯它的其他解決方案

$("div[innerHTML=text]")