2013-04-05 85 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'); 
}); 
相关问题