Locate the immediate parent element and assign a class to it using jQuery

CSS:

<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>

JavaScript:

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

The code works, but it adds the hobi class to all parent divs. I want to add it only to the parent div of text1. How can I fix this?

Answer №1

To apply a specific class to a div containing certain text, you can utilize the :contains selector in conjunction with the appropriate div selector:

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

Check out the live demo here!

Answer №2

When using the jquery selector :contains(), it will match any element that contains the specified string. However, I recommend utilizing the .filter() method instead:

$(".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>

Answer №3

Consider avoiding the if statement in this case as it is not needed.

$(".sonuc").has("span:contains('text1')").parent().addClass('hobi')

Answer №4

In order to locate the specific element with ease, you can utilize a single filter:

$(".sonuc:contains('text1')").parent().addClass('hobi');

Alternatively, if you specifically want to target the first parent element, you can directly employ the :eq() selector:

$(".sonuc:eq(0)").parent().addClass('hobi');

Answer №5

Your goal is to locate the parent element of sonuc, but you are only adding a class to sonuc.

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

Answer №6

Simply include the first() function in your jQuery code snippet:

if ($(".sonuc").has(":contains('text1')").length) {
    $('.sonuc').first().parent().addClass('hobi')
}
.hobi{
color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.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>

Answer №7

Simply merge your current resources.

$('.sonuc').has(":contains('text1')").parent().addClass('hobi');

It's probably not a wise idea to rely on testing text as it may change...

To select the first element from a group of elements, you can:

$('.sonuc').eq(0).parent().addClass('hobi');

or

$('.sonuc:eq(0)').parent().addClass('hobi');

Answer №8

An alternative, more straightforward method that does not involve the use of :contains or .filter() is as follows:

$('.sonuc > span:first').parent().addClass('hobi');

This code snippet targets the first direct descendant span within the .sonuc class. It then uses .parent() to select its parent and adds the class '.hobi' to it.

See the Working JSFiddle Demo


$('.sonuc > span:first').parent().addClass('hobi');
.hobi {
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to programmatically update a webpage using Javascript?

I have been attempting to set up the code in a way that the page automatically changes using setTimeout. However, I am unable to make it work. setTimeout()(page3, 500); function page3() { changepage3('automatic') } Even though my code is str ...

Using Firebase callable functions with React Native

Can I use Firebase callable functions with React Native? I have successfully deployed an onCall function and it is visible in my dashboard. I have initialized the functions using: // Initialize Cloud Functions through Firebase firebase.functions(); The ...

Serving static files with Express JS while using Angular's $locationProvider.html5Mode (express.static)

I have a web application built with Angular and Express JS on the server side. I successfully removed the angular # (hashbangs) by using $locationProvider.html5Mode in my code and setting the base in the header of the HTML. Everything is working perfectly ...

Is there a way to recycle an image and ensure that the web browser only needs to download it once?

Is there a way to effectively reuse the same image multiple times on my website without inefficiently downloading it each time? ...

The validation process is still failing even though the correct credentials have been entered

I'm diving into the world of Javascript and DOM today, but I've hit a roadblock. Can you take a look at this code snippet and help me figure out what's causing me to always end up in the else block, no matter what I input in the text field? ...

Transferring the bundle files of one Next.js app to another Next.js app

Currently, I manage two distinct Next.js applications that handle separate sets of routes. Additionally, I have developed a custom Next.js server that determines which page to display based on the requested URL. I am interested in utilizing the custom ser ...

Using Fabric JS to create a group of multiple objects

Can Fabric JS allow for grouping all objects on the canvas with a click event? ...

Can anyone provide a reference or resource that explains the best scenarios for utilizing display:block, display:inline, and display:inline-block, and the reasons behind their usage?

Can you recommend a quality article discussing the guidelines for using display:block, :inline, and :inline-block in CSS, along with explanations on when to utilize each one? Additionally, in what scenarios should we override the display property through ...

Automatically Switch Font Colors to Red and Green

I am looking to automate the process of changing multiple textbox colors based on the class property. <input type="text" Class="ChangeColor" /> <input type="text" Class="ChangeColor" /> <input type=& ...

Ways to restrict a function to a single DOM element using either its id or class

This script is responsible for dynamically loading pages on my website. It works fine, except that it currently iterates over all anchor tags a on the site, whereas I want it to iterate only through my navigation menu. Here is the navigation menu: <div ...

Reveal a segment of a picture

Is there a way to display only a section of an image using either jQuery or another JavaScript method? For example: image: [ ] [ -------- ] [ - - ] [ - part - ] [ - - ] [ -------- ] [ ...

Safari: The onbeforeunload event

Welcome! To experience the Leave | Stay confirmation box on your page, please make sure you are using Safari 10. I am currently facing an issue with getting the confirmation box to display properly across different browsers. To begin, please visit and l ...

Enhance your jQuery cycle experience with additional scrollHorz effects embedded within every slide

My latest project involves creating a scrollHorz slideshow where I am focusing on animating divs inside each slide. The specific jQuery pseudocode I would like to achieve is as follows: $(".item .top").startSlideHorz(); $(".item .middle .left").delay( ...

Is it possible to alter the page color using radio buttons and Vue.js?

How can I implement a feature to allow users to change the page color using radio buttons in Vue.js? This is what I have so far: JavaScript var theme = new Vue({ el: '#theme', data: { picked: '' } }) HTML <div ...

Looking to personalize the appearance of an iframe using CSS styling?

I am working with an iframe that generates a form, and I would like to customize the CSS of this form. How can I go about editing the CSS? <div class="quiz-container" style="text-align: center;" data-quiz="#######" data-pr ...

Tips for interpreting information from a JSON array that has been stringified, looping through the data, and utilizing it effectively

I'm currently exploring Node JS packages and I need some guidance. Here is an example of the JSON data that I have: [{ "name":"SpiderMan", "description":"Superhero", "head_id":"29", "domain_name":"spiderman.com" }] I am trying to figure out how to ...

Changing from using GET to employing POST

My current Ajax request function is as follows: // JavaScript function myFunc(pid) { $.ajax({ type : "GET", url : "testback.php", contentType : "application/json; charset=utf-8", dataType : "json", data : { ...

Navigating errors during the distribution of numerous messages with SendGrid and Node.js

I have developed a command line application that interacts with a DynamoDB table to extract email addresses for items that have not yet received an email. The process involves creating customized message objects, sending emails using SendGrid's sgMail ...

Performing an AJAX PUT call to a C# server-side controller

I've been encountering an issue while attempting to update database records using AJAX requests. Interestingly, I can successfully insert data with a method similar to the one below, but encounter problems when trying to update or delete entries. Bel ...

Trouble with Express.js and Mongoose: Issue with find() method not returning results for specified variable

For the task I'm working on, my goal is to display items that are only visible to the user who posted them. To manage sessions, I am using Passport.js. The code I have written seems to be functioning well up until the end. app.get('/latestp ...