The function is unable to match the elements using the "this" selector

Greetings! I am facing an issue where I have 3 boxes (divs) containing news articles. Each box has a span with hidden text, and upon clicking the "View More" button, I want to slideToggle the hidden text specific to the clicked box. Initially, I tried assigning variables to each button and span individually, but found this method to be too repetitive and slow. Then, I attempted to use the 'this' selector for better performance, but unfortunately, it did not work as expected. Below is the code snippet:

Check out the JSFIDDLE here

Jquery:

//WORKS
var $span = $('span')[0],$span2 = $('span')[1] ,$span3 = $('span')[2];
      var $button = $('button')[0] , $button2 = $('button')[1],$button3 = $('button')[2];

      $('span').hide();
      $($button).click(function(){
        $($span).slideToggle('fast'); 
      });

       $('span').hide();
      $($button2).click(function(){
        $($span2).slideToggle('fast'); 
      });

       $('span').hide();
      $($button3).click(function(){
        $($span3).slideToggle('fast'); 
      }); 
//DOESNT WORK
$(this).find('button').click(function(){
        $(this).find('span').slideToggle();
      });

HTML:

<div class="holder">
              <div>
                  <h2>Blah</h2>
                  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci in dicta facilis ullam assumenda recusandae cum, quas alias distinctio at mollitia dolore ipsa aspernatur reiciendis. <span>Click For More Temporibus vitae quaerat, consequuntur distinctio.Click For More Temporibus vitae quaerat, consequuntur distinctio.</span></p>
                  <button>Click to see more</button>
              </div>
              <div>
                  <h2>Blah</h2>
                  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci in dicta facilis ullam assumenda recusandae cum, quas alias distinctio at mollitia dolore ipsa aspernatur reiciendis. <span>Click For More Temporibus vitae quaerat, consequuntur distinctio.Click For More Temporibus vitae quaerat, consequuntur distinctio.</span></p>
                  <button>Click to see more</button>
              </div>
              <div>
                  <h2>Blah</h2>
                  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci in dicta facilis ullam assumenda recusandae cum, quas alias distinctio at mollitia dolore ipsa aspernatur reiciendis. <span>Click For More Temporibus vitae quaerat, consequuntur distinctio.Click For More Temporibus vitae quaerat, consequuntur distinctio.</span></p>
                  <button>Click to see more</button>
              </div>
          </div>

CSS:

.holder{
    width:80%;
    margin: 0 auto;
    text-align: center;
}


.holder div{
    width:25%;
    vertical-align: top;

    border:1px solid black;

    display:inline-block;
    padding:20px;
}

button{
    padding:10px 20px 10px 20px;
    background-color:red;
    color:#ffffff;
    border:1px solid #000000;

    cursor:pointer;
    transition:background 0.4s , color 0.5s;
}

button:hover{
    border:1px solid #000000;

    background-color:#ffffff;
    color:red;

}

Answer №1

$('button').on('click', function() {
    $(this).prev().find('span').slideToggle(); //finding the span which is a child of the previous paragraph element
});

Utilize .prev()

Description: Retrieve the immediately preceding sibling of each selected element. If a selector is specified, it will only return the previous sibling that matches the selector.

Then, make use of .find()

Description: Find descendants of each selected element based on a specified selector, jQuery object, or element.

See Demo

Answer №2

Update Jquery code as shown below:

$('span').hide();
$('button').on('click', function(){
    $(this).parent().find('span').slideToggle();
});

See it in action on Fiddle!

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

Combining Sails.js and Angular 2: A Powerful Integration

Trying to incorporate Angular 2 into a Sails Js application, I find myself facing some challenges as a newcomer to both. Following the official tutorial, everything works smoothly in standalone mode with a static http server. However, integrating it into t ...

Dealing with Slow Loading and Partial Data Returns in .NET Core and Ajax

Out of a total of 6 records in the database, only 4 are returning successfully while the remaining 2 are unsuccessful. Upon checking the controller, I found no issues with the data. Additionally, the loading speed seems to be slow despite the small number ...

Secure Access with Skype Bot Verification

Recently, I managed to set up a NodeJS bot to synchronize messages between Discord and Skype chats. Although I am relatively new to Javascript and completely unfamiliar with NodeJS, the existence of a framework called Spype has been quite beneficial. The i ...

Understanding HTML through regular expressions

Can anyone assist me in finding the regular expressions needed to parse an HTML file for a program I'm working on? Here are some specific ones I'm looking for: <div> <div class=”menuItem”> <span> class=”emph” Any str ...

creation of pie chart embedded within a donut chart utilizing the functionalities of chart js

For my project, I have been utilizing chart js to create visually appealing charts. Currently, I am faced with the task of drawing a pie chart within a donut chart similar to this example: https://i.sstatic.net/AO0os.png The data in the donut chart is not ...

The ultimate tool for creating AJAX applications with minimal effort - a graphical development environment that

Does anyone know of a convenient tool that can help in quickly creating the front-end AJAX for an administrative interface? I'm looking for something like a "Javascript Generator" found in Microsoft Visual development environments. A tool where I can ...

Angular side indicators (CSS)

On my HTML page, I have a collection of photos that I want to enhance using CSS. Specifically, I am seeking guidance on how to add a "Featured" marker in the top corner of some of the images, similar to the red stripe shown in this example - Although I co ...

We are hosting an event focused on DOM text selection outside of Input or TextArea elements

I need help finding a Javascript event that triggers when a user highlights paragraph text with their mouse on a web page. Once the text is highlighted, I want to access it using window.getSelection(). Just to clarify, I am not looking for ways to capture ...

Issue encountered with AJAX multiple image uploader

I'm attempting to create an PHP and JavaScript (jQuery using $.ajax) image uploader. HTML: <form method="post" action="php/inc.upload.php" id="upload-form" enctype="multipart/form-data"> <input type="file" id="file-input" name="file[]" a ...

Determining the container height for every two-image row

I am currently working on a project for this website. My focus right now is on resizing vertical images using the following script: function Gallery(selector) { this.add_module = function (type, image) { var portrait_text = image.next('.portr ...

When the browser is dragged, the background image starts to overlap the following section

I am currently working on making my webpage mobile-friendly, or what is commonly referred to as mobile-compatible. One issue I am facing with my page is that it appears fine at a specific size, but when I resize the browser window, the background image ove ...

Forward the value of the selected radio button

Currently, I am focusing on this code snippet. <html> <script> var submit = document.getElementById('btnFormSubmit'); submit.addEventListener('click', submitForm); function submitForm(event){ event.preventDefault(); event. ...

Acquire the payload from the post

After using jQuery to ajax post data to a nodejs webserver, I encountered a problem with retrieving the payload. The nodejs documentation was unhelpful, and I struggled to access the data even after dumping the request object to the debugger console. How c ...

Padding issues in navbar-expand for Bootstrap 4

I'm encountering a strange issue with padding in my navbar that seems to be dependent on the navbar-expand property. For instance, when I set it to MD, it appears like this: https://i.sstatic.net/czytc.png As you can see, the logo and menu button d ...

"MongoDB's .find function functions properly in the shell environment, but encounters issues when

As a newcomer to Node Express Mongo, I decided to venture into creating my own website after following tutorials. The page I'm working on is a login page. While other people's code has worked for me, my attempt didn't go as planned. Even con ...

The concept of accessing a reference in JavaScript

Take a look at this code snippet: http://jsfiddle.net/GKBfL/ I have a function called collection.prototype.add and I want it to return a reference so that the final alert will show testing, testing, 123, testing. Any ideas on how to achieve this? Here i ...

Unable to trigger @click event on nuxt-link component within Nuxt 3

As per a Nuxt 2 question on Stack Overflow, it was suggested that the following code should prevent nuxt-link from navigating to a new page: <nuxt-link :to="`/meet`" class="group font-normal" @click.native="event => event.pre ...

What is the best way to convert AMD-written code to CommonJs format without needing to bundle it together?

Currently, I have a project that was initially written for browsers using AMD modules. Now, I am in need of running the same code in Node.js. This requires me to rewrite each file to use CommonJS modules instead. I did attempt to use webpack, but it prov ...

Tips for creating a validator function in Angular that only allows whole numbers between 0 and 30, excluding decimals

When a user enters a value between 0 and 30, the input should accept whole numbers like 0, 2, or 20 but not decimal values such as 20.1 or 0.1. I tried using validators min(0) and max(30), but they still allow decimal values. I need a validator that restr ...

Include a personalized header in $http

In my factory, I have multiple functions that follow this structure: doFunction: function () { return $http({ method: 'POST', url: 'https://localhost:8000/test', data: {}, headers: { "My_Header" ...