Can you show me a way to use jQuery to delete several href links using their IDs at once?

Currently facing a challenge with removing multiple href links that share the same ID. Here is a snippet of my code:

    $('.delblk').click(function(e) {
        e.preventDefault();

        var id = $(this).attr('id').substr(7);

        $.getJSON("../ajax_blocked.php?op=delete&id="+id, function(data) {
        if (data) {

            $("#delblk_"+id).each(function() {
                $(this).remove();
            });
        }
    });

This is how my HTML appears:

<a href="sent.php" id="delblk_7" class="delblk" ><span class="label label-important">Unblock</span></a>
<a href="sent.php" id="delblk_7" class="delblk" ><span class="label label-important">Unblock</span></a>
<a href="sent.php" id="delblk_8" class="delblk" ><span class="label label-important">Unblock</span></a>

The problem lies in it only removing the first href link and not both. What could I be overlooking?

Answer №1

Issue Explanation

The problem arises when an id is not unique within your document, in such cases, it's better to use the class attribute instead.

Hence, using the id (#) selector can lead to issues because of non-uniqueness.

Yet, you can utilize the Attribute Equals Selector to navigate through your elements. Feel free to refer to my example and this jsFiddle Demonstration

w3c states that the id attribute signifies a distinct identifier for an HTML element (the id value should remain unique throughout the HTML document).

Example

$("a[id='delblk_"+id+"']").each(function() {
    // ...
});

Further Details

Answer №2

It is important to note that having multiple elements with the same id is not allowed in HTML. Instead, use classes for styling and identification purposes.

IDs should be unique within a document to avoid conflicts. Selecting elements by ID will only target the first element found in the DOM, so it's best practice to keep IDs unique.

Documentation

Think of each HTML page as its own country, and ids as unique identifiers for individuals. Just like how everyone in a country has a different identity, each element in an HTML document should have a unique id.

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

Reactivity in Vue.js powered by ES6 classes

I am attempting to create a computed property in Vue.js that is associated with an ES6 class. Here is an example of my Vue instance setup: ... props: ['customClass'], computed: { localClass: { get() { return this.custom ...

Sending data from a Node.js backend to a React.js frontend using res.send

How can I pass a string from my nodejs backend using res.send? app.post("/user", (req,res) => { console.log(req.body.email); res.send('haha'); }); I need to perform certain operations on the front end based on the value of the string retriev ...

Should all images be set to 100% width with a standard Bootstrap configuration?

For my website project, I decided to incorporate the Bootstrap carousel into the header using version 3.0.3 of Bootstrap. Everything seemed to be functioning correctly until I noticed a strange issue with the image sizes on the page. Initially, all the ima ...

Tips for effectively passing "this" to direct the event initiator in react js?

I'm facing an issue where I am attempting to send a buttons object to a function and then access its properties within that function. Here's my button : <RaisedButton label="Primary" id = "1" onTouchTap={()=>this.buttonPress(this)} prima ...

The best approach for setting a select value and managing state in React using TypeScript

Currently, I am in the process of familiarizing myself with TypeScript within my React projects. I have defined a type for the expected data structure (consisting of name and url). type PokedexType = { name: string; url: string; } The API respon ...

Retrieving the contents of a unique 404 error page using ajax

Currently attempting to retrieve the content of a custom 404 page through ajax (I need to extract a counter value from this page using Greasemonkey). Regrettably, jQuery's .fail method in ajax does not provide the option to access the page's con ...

Sending the format of the display value to an Angular component

Looking for a way to pass display value formatting to an Angular component. Here are a couple of examples: format="'(utc, offset) location (tz)'" === '(UTC -04:00) New York (EDT)' or format="'(tz, offset) location'" === &a ...

Numerous Customized Google Maps

On my contact page , I have a Google Map V3 that is styled and mostly functional, except for some sprite image display issues. Now, I need to include the same JSON data in two separate maps on my showrooms page . How can I style multiple maps with differen ...

Is having async as false really detrimental?

Splitting my inquiry into two sections. Within my website, I am dynamically generating some divs by utilizing ajax post requests to retrieve data from the database. Following is the structure of my setup. <html> <body> <script type=" ...

Tips on retrieving JSON data in a Bottle (Python framework) using a Jquery script

I'm currently facing an issue where I am sending a POST request with JSON data using AJAX jQuery, expecting to receive it on my API server built with Bottle. However, the JSON data is being sent from the client side but isn't being received by th ...

An error of type 'TypeError' has occurred, where it is unable to access the property 'render' of an undefined element in

I'm using a function in my controller to render the "result" in my "home-page" view, which is calling my model to execute the query. exports.searchNoms = (req, res) => { getDatabaseModel.searchNoms(req).then(function(result) { console.l ...

Guide on transforming a PHP array encoded in JSON into a JavaScript array

After fetching a JSON encoded array via AJAX from a PHP file, I need to manipulate it as an array in JavaScript. How can I achieve this? Here is my AJAX call to the PHP File: $.ajax({ type:"POST", url:"ajaxfetch.php", success:function(re ...

Using Three.js to seamlessly transition from one Panorama Cube to another with a smooth zoom-in effect

As a newcomer to Three.js, I am currently experimenting with an example featuring a set of 6 image cubes for a panorama effect. This allows users to pan, zoom in, and zoom out around the cubes. If you're interested, you can check out the example here ...

Evolutionary JavaScript Adaptations

I am currently working on an HTML project that involves the use of JavaScript with JQuery. In my project, I will be including a map showcasing different images such as 'Abstract', 'Animals', 'Beach' and more. var images = { & ...

Navigating in next.js

Whenever I run my program, it displays the following error message: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component ...

Achieving equal alignment of items with flexbox

As someone who is just starting to learn about HTML and CSS, I have been working on creating toggle buttons that I want to align dynamically in the center of the screen. I recently discovered flexbox which has made this process easier for me. However, one ...

having difficulty with an intricate flexbox grid within another flexbox

I attempted to create a grid-like pattern using a negative margin based grid system (Susy) but was unsuccessful. Next, I tried employing flexbox for the task. However, I'm unsure if it's achievable. My initial idea was to have 2 columns (side A ...

Creating a carousel in AngularJS using ng-repeat without resorting to jQuery

Looking for a solution to display elements on my page with ng-repeat in a carousel-like fashion. Each element should have a photo, short description, and reveal a long description on click. It's important that it's mobile-friendly so users can sw ...

Tracking the progress of file uploads using Ajax

Currently, I am working on integrating file upload using Ajax and Php on my local Apache server. This is strong text. $('.uploadButton').click(function(){ var formData = new FormData($(this).closest('.fileUploadFor ...

The challenges encountered with JSONP/Ajax Script - displaying 'Undefined'

I need help retrieving data from a webserver that I don't have control over. I've searched online but haven't found a solution yet. I've tried various codes, with and without DataTables. If anyone could provide guidance on where to go ...