Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery if element contains text, add class to parent div

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 !

like image 980
user3263728 Avatar asked Feb 02 '14 20:02

user3263728


3 Answers

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

like image 70
Satpal Avatar answered Nov 15 '22 02:11

Satpal


You don't have to check the length, it either returns an element or it doesn't, and you'll have to use closest(), as #post-item is not the immediate parent element.

I used classes as you can not use duplicate ID's

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

FIDDLE

like image 35
adeneo Avatar answered Nov 15 '22 02:11

adeneo


Following should be your javascript.

$(document).ready(function () {
    jQuery('a:contains("Sponsored")').closest('#post-item').addClass('sponz');
});

Demo

like image 1
Krishanu Dey Avatar answered Nov 15 '22 00:11

Krishanu Dey