Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
193
rated 0 times [  200] [ 7]  / answers: 1 / hits: 31026  / 11 Years ago, sun, february 2, 2014, 12:00:00

I need to add a class to a parent div if one of the children elements contains the word Sponsored.



<div id=post-item>   
<span class=tags>
<a href=#>Blogs</a>
</span>
</div>

<div id=post-item>
<span class=tags>
<a href=#>Sponsored by Lorem Ipsum</a>
</span>
</div>


I am currently trying to use parent().addClass but it's not working for some reason. You can see an example in this fiddle: http://jsfiddle.net/VrPdF/



if (jQuery('a:contains(Sponsored)').length) {
jQuery(this).parent('#post-item').addClass('sponz');

}


Any and all help would be greatly appreciated - thanks !


More From » jquery

 Answers
16

IDs must be unique, so use class to identify parent. You can use .closest() to identify parent with class post-item.



HTML



<div class=post-item>   
<span class=tags>
<a href=#>Blogs</a>
<h3>Lorem</h3>
</span>
</div>

<div class=post-item>
<span class=tags>
<a href=#>Sponsored by Lorem Ipsum</a>
</span>
<h3>Lorem</h3>
</div>


JavaScript



jQuery('a:contains(Sponsored)').closest('.post-item').addClass('sponz');


DEMO






:has() Selector can also be used




Selects elements which contain at least one element that matches the specified selector.




jQuery('.post-item:has(a:contains(Sponsored))').addClass('sponz');


jsFiddle


[#72780] Friday, January 31, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rashawn

Total Points: 451
Total Questions: 83
Total Answers: 83

Location: Egypt
Member since Tue, May 3, 2022
2 Years ago
rashawn questions
;