简体   繁体   中英

Can't remove element with jquery's remove()

I'm making a greasemonkey script for this website: http://tinyurl.com/websiteasdasd and I want to remove the element rodape-ao-vivo , problem is that doing $("#rodape-ao-vivo").remove(); is not working, however, if I do something like

setInterval(function() {
        $("#rodape-ao-vivo").remove();
    }, 1000);

it works just fine, so I'm basically asking you to help me understand what's going on here. Maybe it's just a small stupid thing but I'm sleepless and really want to get this done.

This DIV is dynamically generated by script, to remove it, you need to wait until this element is availabe in DOM, eg if for some reason other answers don't work: {or use DOM ready handler}

$(window).on('load', function () {
    var interval = setInterval(function () {
        if ($("#rodape-ao-vivo").length) {
            $("#rodape-ao-vivo").remove();
            clearInterval(interval);
        }
    }, 100);
});

Hmm, perhaps you are trying to remove the element before it's created? (The delay helps because in that time the element gets created and you can remove it)

You probably try to remove the element before it even exists. Adding one second delay gives the browser enough time to render the element, so you can remove it then. But it's not guaranteed to work, because one second may not be enough to render that element (slow connection, for example).

So you should make sure the document is ready, jQuery's way to do this is:

$(function() {
    $("#rodape-ao-vivo").remove();
});

Or you can wait for the whole document to load:

window.onload = function() {
    $("#rodape-ao-vivo").remove();
}

如果您在页面加载时执行此操作,则使用document.ready();包装代码。

$(document).ready(function(){$("#rodape-ao-vivo").remove();});

Please make sure that all the elements gets loaded before your use them.So wrap your code inside function which will ensure your elements has been attached to DOM

$("#rodape-ao-vivo").remove(); //will probably will give you an error.

$(function() {
    $("#rodape-ao-vivo").remove();
}

Or ,

$( document ).ready(function() {
    $("#rodape-ao-vivo").remove();
})

Or,

jQuery( document ).ready(function( $ ) {
    $("#rodape-ao-vivo").remove();
});

Or,

window.onload = function() {
    $("#rodape-ao-vivo").remove();
}

But when you do ,

setInterval(function() {
        $("#rodape-ao-vivo").remove();
}, 1000);

This will give an element time to get load in your DOM .So It working fine.But instead of using setInterval you can use function listed above

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM