diegales
diegales

Reputation: 25

jQuery remove() not removing on first attempt even though the element to be removed is visible at the time

So, I have an ajax call with async set to false to load content into a particular div. Among this content there is a button with id='cancelbtn. Problem is, if I call remove, it is not removed, even though the console prints the element correctly one line before. Weirdly, if I repeat the remove line a number of times, then it works 'as expected'. Any ideas? The code from the ajax call is:

    $.ajax ({
    url: 'contentincludingthecancelbtn.html',
    async: false,
    success: function(data){
        $('#divCont').html(data); 
        console.log($('#cancelbtn'));
        $('#cancelbtn').remove();
    });
    });

The button displays at the end. This used to be a direct load call (not working either) changed in order to try async:false but no luck.

Upvotes: 0

Views: 1869

Answers (3)

ismnoiet
ismnoiet

Reputation: 4159

You should be careful when using ids because they are supposed to be unique so we don't have two elements with the same id even when we have two elements with the same id for example

$('body').append('<p id="para">text</p><p id="para">text</p>');

now the following code :

$('#para').click(function(){console.log('just clicked ');});

will work just for the first element which is the first paragraph

note : $('#divCont').find('#cancelbtn').remove() : is good to make sure that we deleted all the elements with the id divCont but in the other hand it doesn't make sense because .find jquery method is used when we expect the matched elements to be greater than 1 while we know that ids should be unique so $('#divCont').remove(); is enough

Upvotes: 0

Abs
Abs

Reputation: 455

try to remove button on complete event like this:

$.ajax ({
    url: 'contentincludingthecancelbtn.html',
    async: false,
    success: function(data){
        $('#divCont').html(data); 
        console.log($('#cancelbtn'));
        },
    complete: function(){
        $('#cancelbtn').remove();
        });
    });

Upvotes: 1

Peruggia
Peruggia

Reputation: 191

Maybe you have two elements with the same ID, so the jQuery is removing the first one and then the second (the one you want to remove).

To solve this you could change the element's ID or try this code:

$('#divCont').find('#cancelbtn').remove();

Upvotes: 2

Related Questions