2013-04-05 81 views
0

我怎樣才能得到所有的HTML父元素有一個叫做".example"的css類和他們的孩子<a></a>元素包含字符串值說sample-sectionhref屬性通過jQuery?如何獲取具有某個類的所有父元素,並且其子元素通過jQuery在其給定屬性中具有某個字符串值?

下面是一個例子:

<li class="example"> 
    <a href="root/sample-section/p01">Page 1</a> 
</li> 
<li class="example"> 
    <a href="root/sample-section/p02">Page 2</a> 
</li> 
<li class="example"> 
    <a href="root/another-section/p01">Page 1</a> 
</li> 
<li class="example"> 
    <a href="root/another-section/p02">Page 2</a> 
</li> 

我希望能夠通過jQuery我上面提到的,以獲得第一,在這個例子中,第二<li></li>元素(它們包含字符串「樣品部分」)標準並向他們添加某些其他類。提前致謝!

回答

0

^使用屬性選擇器,其獲取與給定文本

所有的HREF開始嘗試這個..

console.log($('a[href^="root/sample-section/"]').parent()) 

*選擇所有元素具有包含值的指定屬性給定的子字符串。

console.log($('a[href*="sample-section"]').parent()) 

fiddle here

0

試試這個:

$('li.example > a[href*="sample-section"]').closest('li.example'); 
+0

'〜='這裏是錯誤的選擇。改用'* ='。 – j08691 2013-04-05 18:39:15

+0

OP確實指出錨點應該是「li」的(直接)孩子。 – Blazemonger 2013-04-05 18:40:31

0
$('li.example a[href*="another-section"]').each(function() { 
    $(this).closest('li'); 
}); 
相關問題