Display or conceal script for individual elements, not universally

I am working on a news page that has a Show/Hide script implemented to handle long content. However, the current script is applied globally to all content and I would like it to only apply to one specific element or the nearest element.

Here is the current script:

$(document).ready(function(){ 

   $(".btn1").click(function(){
      $("p.esl").hide();
   }); 

   $(".btn2").click(function(){
      $("p.esl").show();

   });
});

Website:

P.S. I am still learning jQuery so my skills are quite limited.

Answer №1

If you're encountering an issue, the following code can help address it.

$(document).ready(function(){ 

   $(".btn1").click(function(){
      $(this).parents(".news-item").find(".esl").hide();
   }); 

   $(".btn2").click(function(){
      $(this).parents(".news-item").find("p.esl").show();
   });
});

This snippet specifically targets and hides p tags within a news item section, ensuring only those elements are affected.

Answer №2

Prefer using id instead of class

$(document).ready(function(){ 

   $("#btn1").click(function(){
      $("p#esl1").hide();
   }); 

   $("#btn2").click(function(){
      $("p#esl1").show();

   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id = "esl1">Here is my paragraph!!!! Hi I can hide</p>
<p id = "esl2">Here is my paragraph!!!! Hi I won`t hide</p>
<button id = "btn1">hide</button>
<button id = "btn2">show</button>

Perhaps this reference here, will provide more insight.

Answer №3

When facing situations like this, following the advice given by @naveen is the most effective approach.

$(document).ready(function(){ 

   $(".btn1").click(function(){
      $(this).parents(".news-item").find(".esl").hide();
   }); 

   $(".btn2").click(function(){
      $(this).parents(".news-item").find("p.esl").show();
   });
});

By using this method of traversing to a specific part and locating its child element, the problem with event click can be resolved.

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

Can native types in JavaScript have getters set on them?

I've been attempting to create a getter for a built-in String object in JavaScript but I can't seem to make it function properly. Is this actually doable? var text = "bar"; text.__defineGetter__("length", function() { return 3; }); (I need th ...

There seems to be a JSON syntax error on the website for tracking Covid-

Hi everyone, I'm currently working on a Covid-19 tracker website and facing an issue that says: 'SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data' ; Being new to web development, I am unsure about what&apo ...

Uh-oh! An unexpected type error occurred. It seems that the property 'paginator' cannot be set

I am developing a responsive table using Angular Material. To guide me, I found this helpful example here. Here is the progress I have made so far: HTML <mat-form-field> <input matInput (keyup)="applyFilter($event.target.value)" placeholder ...

Activate a button on-the-fly

When the page loads, I have an empty array. Since there are no values stored in this array, I disabled the button using ng-disabled="array1.length==0". Now, on the page that opens up, there are four drop downs present. My goal is to enable the button once ...

Interpret JSON data with jQuery

I am trying to access the JSON array below: [{"bus_code":"1103030017","bus_name":"Tony\u0027s Sports Bar \u0026 Grill","first_name":"","last_name":"","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7b0f141502 ...

Attempting to modify code to produce HTML output using Selenium in Python

I am currently using Selenium to scrape information from Facebook groups: with open("groups.txt") as file: lines = file.readlines() total = len(lines) count = 1 for line in lines: group_id = line.strip().split(".com/")[1] ...

Delay in only a portion of the AJAX response

I created a chat application that is functioning correctly, but I am encountering an unexpected behavior. When a user sends a message, the user's name, time, and message should be displayed in order. However, currently, it seems like the username and ...

Button Click Does Not Trigger Bootstrap Modal Display

This is a sample Bootstrap document that includes JS and CSS files to display a list properly in Bootstrap. However, the Modal does not appear when clicking on Launch demo modal. No JavaScript errors are displayed in the Console. Can you help troubleshoot ...

Creating an alarm clock with customizable time and date formats using ReactJS with Material-UI integration

Here is the code I have written: const date = new Date(); const currentTime = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`; const getDay = `${date.getDay()} ${date.getMonth()} ${date.getDate()}`; return ( <Box> < ...

Issue with getting Bootstrap sticky-top to function on sidebar column

My goal is to implement a sticky sidebar on the right side of the page. The sidebar menu is contained within a grid column. I have attempted to utilize the sticky-top class, following the guidance provided in this question, but unfortunately, it does not s ...

Is there a way to extract the "validade" value from the array and retrieve it exclusively?

The following array contains data: {"status":true,"data":[{"id":1,"pessoa_id":75505,"created_at":"2022-02- 01T17:42:46.000000Z","holder":"LEONARDO LIMA","validade&quo ...

Tips for utilizing jQuery buttons to submit forms in PHP

I'm struggling to submit the form using PHP from a button in jQuery. I've tried adding an ID for the button, but I can't seem to submit the values. Since I'm new to jQuery, this task is proving to be a bit challenging. Can anyone provid ...

Discover the process of transitioning your animations from Angular to CSS

I have successfully implemented a fade-in/out animation using @angular/animation, but now I am looking to transfer this animation to CSS and eliminate the dependency on @angular/animation. Here is my current animation setup (triggering it with [@fadeInOut ...

Header text aligned with image to accommodate parent size

Having trouble aligning an image/logo next to my header text while maintaining its aspect ratio and fitting within the container size. The goal is to have both the text and image horizontally centered. The parent div cannot have a fixed height as it needs ...

Issue encountered: The differ cannot recognize the provided object '[object Object]', which is of type 'object'. NgFor is limited to binding Iterables only

I have been following a tutorial on Ionic created by Paul Halliday, focusing on a shopping list project that utilizes Firebase and Angular. However, I am encountering an error every time I try to run the application: Error: Uncaught (in promise): Error: ...

Guide on executing YUI tests in headless mode and recording outcomes in a log document

I currently have some YUI tests that I need to run in headless mode. Right now, these tests are executed by launching their corresponding TestFileName.html. As a result, the browser displays the test results with green and red icons along with messages ind ...

Why are all the values in my list appearing as undefined after parsing with JSON?

Just starting out with this project. I'm attempting to print a list, where the names come from a button. However, all the names are showing up as undefined. I suspect it has something to do with local storage, but I can't pinpoint the issue. < ...

Crop images in a canvas using a customized rectangle with the help of JQuery

I am trying to crop an image inside a Canvas element using a selection rectangle. My project utilizes jQuery and I am in search of a plugin that can help me implement this custom selection rectangle on the canvas itself, not just on images. Are there any ...

Is there a way to launch iframe links in the parent window of an Android native app?

I'm currently working on developing a directory-style application, and I am using iframes to embed other websites into the app. I would like the embedded site links to open within the parent window. In the Progressive Web App version, everything is w ...

What is the best way to extract URL query parameters and store them in a MySQL database using Node.js and Express

I am working on a project where I need to store specific information like names and widths from the URL query into my MySQL database. The format of the URL query should resemble this: /register?name=XXXX&width=###.### However, I seem to be facing ch ...