Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find first parent and add class via jQuery

HTML:

<div class="views-row views-row-10 views-row-even views-row-last">    
  <div class="sonuc">        
    <span>text1</span>  
  </div>
</div>
<div class="views-row views-row-11 views-row-even views-row-last">    
  <div class="sonuc">        
    <span>text2</span>  
  </div>

JS:

if ($(".sonuc").has(":contains('text1')").length) {
  $('.sonuc').parent().addClass('hobi')
}

Its work but add hobi class all parent divs. But I want add only text1's parent div. How can I fix it?

like image 530
Bariskonat Avatar asked Dec 17 '14 11:12

Bariskonat


People also ask

How do I find a specific parent in jQuery?

The parents() is an inbuilt method in jQuery which is used to find all the parent elements related to the selected element. This parents() method in jQuery traverse all the levels up the selected element and return that all elements.

What is the use of parent () and child () method in jQuery?

It is a jQuery Selector used to select all elements that are the direct child of its parent element. Parameter Values: parent: Using this, the parent element will be selected. child: Using this, the direct child element of the specified parent element will be selected.

How do I get grandparents in jQuery?

jQuery parentsUntil() Method The parentsUntil() method returns all ancestor elements between the selector and stop. An ancestor is a parent, grandparent, great-grandparent, and so on.

What is add class in jQuery?

The addClass() method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more class names to the class attribute. Tip: To add more than one class, separate the class names with spaces.


2 Answers

You can use :contains selector along with required div selector:

 $('.views-row:contains(text1)').addClass('hobi');

Working Fiddle

like image 130
Milind Anantwar Avatar answered Oct 06 '22 05:10

Milind Anantwar


jquery selector :contains() match any element that contains the string. I suggest to use .filter():

$(".sonuc span").filter(function() {
  return this.innerText === "text1";
}).parents("div.views-row").addClass("active");
.active {
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="views-row views-row-10 views-row-even views-row-last">
  <div class="sonuc">
    <span>text1</span> 
  </div>
</div>
<div class="views-row views-row-11 views-row-even views-row-last">
  <div class="sonuc">
    <span>text2</span> 
  </div>
  <div class="views-row views-row-11 views-row-even views-row-last">
    <div class="sonuc">
      <span>text11</span> 
    </div>
like image 30
Alex Char Avatar answered Oct 06 '22 03:10

Alex Char