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?
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.
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.
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.
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.
You can use :contains
selector along with required div selector:
$('.views-row:contains(text1)').addClass('hobi');
Working Fiddle
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With