conceal the present element using jQuery while dealing with numerous identical elements

When clicking on an element, I am attempting to hide that specific element. However, all elements share the same id and I need each one to hide individually upon click.

Typically, I would use PHP in a foreach loop to add an incremental value to each ID. Unfortunately, this is not possible in this case.

This is my current setup:

<div id="container">
    <a href="#" class="hideme">hide me</a>
    SOME TEXT
</div>
<div id="container">
    <a href="#" class="hideme">hide me</a>
    SOME TEXT
</div>
<script type="text/javascript">
$(".hideme").click(function(){
    $(this).hide();
});
</script> 

Is there a way in jQuery to hide only the element being clicked? Currently, my code hides only the first element.

Example: https://jsfiddle.net/2rnw224b/

Answer №1

A more efficient approach is to use classes instead of multiple elements with the same id. By attaching an event listener to all elements with the same class name, you can easily remove the container when clicked.

Check out the example below. I've also made changes to your fiddle.

$('.hideme').click(function(e){
  e.preventDefault()
  $(this).hide()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="container">
    <a href="#" class="hideme">hide me</a>
    SOME TEXT
</div>
<div class="container">
    <a href="#" class="hideme">hide me</a>
    SOME TEXT
</div>
<div class="container">
    <a href="#" class="hideme">hide me</a>
    SOME TEXT
</div>
<div class="container">
    <a href="#" class="hideme">hide me</a>
    SOME TEXT
</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

Error encountered while parsing JSON data from LocalStorage

Storing an object in localStorage can sometimes lead to unexpected errors. Take this example: function onExit(){ localStorage.setItem("my_object","'" + JSON.stringify(object) + "'"); } When retrieving this data from localStorage, it may loo ...

Configuring Braintree Client with JS v3 - encountering a null payment_method_nonce causing issues with form submission

I have successfully integrated Braintree into my Laravel 5.2 app using JS v2 client setup, but now I want to upgrade to v3. I have customized the code from the docs as follows: <form id="checkout-form" action="/checkout" method="post"> <div id= ...

The @Mui datepicker seems to be causing some trouble with the react-hooks-form integration

Below is a code snippet where I showcase working and non-working sections (commented out). <Controller control={control} name="DOB" render={({ field }) => ( <LocalizationProvider dateAdapter={AdapterDayjs}> <DatePic ...

Angular - send multiple HTTP requests for the length of an array and combine the responses into one array

Exploring angular for the first time and dabbling with the trello API. I have an array containing some list IDs that I need to make HTTP GET calls for, equal to the length of the array. For instance, if there are two IDs in the array, then the HTTP call sh ...

Is the neglected property being discarded?

First things first, let's talk about my class: class FavoriteFooBar { ... isPreferred: boolean = false; constructor() { this.isPreferred = false; } } Using a utility library called Uniquer, I arrange a list of FavoriteFooBar instances to pr ...

Setting the value of an Html.DropDownlist using ViewBag in a controller action

Currently, I am working on a project where I have a drop-down list (@Html.DropDownList) on my view with initial null values. The idea is to populate the values of this list based on the selected value from another drop-down list. Below are my two drop-down ...

Responsive design element order rearrangement

My code example is as follows: <div class="info-container"> <span class="item1">item1</span> <a class="item2" href="#">item2</a> <a class="item3" href="#">item3</a> </div> I want to rearran ...

Having issues with jQuery Validate not validating fields when using an onclick handler?

I am looking to implement an onclick event handler for validating form fields using jQuery Validate. Here is the code I have: <input type="text" id="Name" name="Name"> <a class="btn btn-primary js-add-names" href="#">Add Names</a> &l ...

Steps to eliminate a list-divider in jQuery Mobile when removing the list item

I need help with a situation involving groups of list items (li). When I delete all the "li" in a group, I want to also remove the list-divider that separates them. For example, if there are 3 "li" after a list-divider, and I delete each "li" one by one, w ...

Creating a duplicate of the Object in order to include a new key and value pair

While pre-fetching a product from a database using mongoose along with next.js and react-query, I encountered a situation where I had to perform a deep copy of a nested object to successfully add a key-value pair to it. Without this deep copy, the operat ...

"Utilize Selenium to navigate and select a menu option with a

In my dropdown menu, I am trying to use Selenium to move the mouse to the Documentation menu item and click on the App Configuration option within it. The mouse hover function is working properly, but I am unable to click on the App Configuration element. ...

Unraveling the Enigma of CSS Grid Whitespace

I'm facing an issue while trying to construct a grid of images using CSS Grid. Interestingly, I am encountering mysterious white space around the first two items in the grid. Upon inspecting the images, I am unable to identify any source of this white ...

React Material UI DataGrid: Error encountered - Unable to access property 'useRef' due to being undefined

The challenge at hand Currently, I am faced with a dilemma while attempting to utilize the React DataGrid. An error in the form of a TypeError: Cannot read property 'useRef' of undefined is appearing in my browser's stack trace. https://i.s ...

Having difficulties understanding JSON and JSONP

I'm completely new to working with JSON and I am really struggling with making a cross-domain request. It's getting frustrating for me :( This is the code I currently have: $.getJSON('http://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0 ...

Tips for utilizing a Three.js curve to guide the movement of a mesh along a specified path

Developing an animation, currently at this stage: http://jsfiddle.net/CoderX99/66b3j9wa/1/ Please avoid delving into the code, it's written in CoffeeScript and may not be beneficial for your mental well-being. Imagine a "nordic" landscape with ship ...

Error during Webpack Compilation: Module 'jQuery' not found in Travis CI with Mocha Test

I've been struggling to automate tests for my repository using mocha-webpack and Travis CI. The local machine runs the tests smoothly, but Travis CI hasn't been able to complete them yet due to an unresolved error: WEBPACK Failed to compile wit ...

Effortlessly switch between CSS animation styles while adjusting animation settings

My HTML element with animation is defined as follows: <div id="box"></div> The box starts by moving 200 pixels to the right, taking 4 seconds to complete. .anim { animation-name: anim; animation-duration: 4s; animation-t ...

Is it possible to replicate, modify, or recycle a purely HTML and CSS component in Angular?

On my Angular website, I am looking to reuse a component across more than 30 pages. While the majority of the pages have similar CSS, the content inside varies. I know I can simply insert <app-example></app-example> on all the pages, using < ...

JavaScript, JQuery, and the Observer Design Pattern

Currently, I am in the process of developing a third-party application specifically for certain websites using Jquery. Lately, I have incorporated rx.Observable into my project. However, grasping the utilization of this new JS library has proven to be qui ...

The module 'myapp' with the dependency 'chart.js' could not be loaded due to an uncaught error: [$injector:modulerr]

Just starting out with Angular.JS and looking to create a chart using chart.js I've successfully installed chart.js with npm install angular-chart.js --save .state('index.dashboard', { url: "/dashboard", templateUrl ...