Reputation: 3776
I have a problem that I'm trying to solve, the current way of doing it requires that I remove elements.
<div id="toremove">
// some JavaScript here
</div>
So I have a function that does something nice, then when that finishes I'd like it to remove the "toremove"
element. I have looked at the jQuery documentation, similar posts allover the Internet but nothing seems to work.
Here's what I'm doing and have tried:
$("#toremove") = $()
$("#toremove").empty();
$("#toremove").remove();
Nothing seems to work for me, any help is appreciated.
Upvotes: 25
Views: 67451
Reputation: 5256
Maybe you are removing the div
when its not even created.
do something like this :
$(function(){
$("#id").remove();
});
This will make sure the DOM is ready.
Also see to it that your id is unique!
Upvotes: 3
Reputation: 7
Use CSS: it's much simpler, and works even for dynamic elements (JSP, etc.). One bad thing: the no-displayed element still exists in the page source.
<style>
#toremove {
display: none;
}
</style>
Upvotes: 0
Reputation: 8253
You can do other of the way to deal with this issue, I will show you I know as following.( please pick anyone up you like)
<html>
<body>
<div id="toremove">
...some javascript here....
</div>
</body>
</html>
<script src="jquery-3.3.1.min.js"></script>
<script>
$('#toremove').html(''); // option 1
$('#toremove').attr('style', 'display:none') // option 2
$('#toremove').attr('style', 'visibility:hidden') // option 3
$('#toremove').remove(); // option 4
$('#toremove').hide(); // option 5
</script>
Upvotes: 3
Reputation: 824
Give this a try:
<div id="toremove">
...some javascript here....
</div>
Corresponding jQuery:
$("#toremove").click(function() {
$("#toremove").remove();
});
Working Demo: http://jsfiddle.net/86z93dzk/ (notice that the JS is loaded onDomready
)
Thus, in your case, you could put the jQuery code anywhere and wrap it with $(document).ready
:
$(document).ready(function() {
$("#toremove").click(function() {
$("#toremove").remove();
});
});
Upvotes: 0
Reputation: 678
$('#toremove').remove();
should do what you need. Are you sure there isn't a problem elsewhere in your code?
Upvotes: 51