marko
marko

Reputation: 3776

jQuery: remove element by id

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

Answers (6)

hityagi
hityagi

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

Leopold Cat
Leopold Cat

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

Willie Cheng
Willie Cheng

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

PaulDapolito
PaulDapolito

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

Anthony Martin
Anthony Martin

Reputation: 678

$('#toremove').remove(); should do what you need. Are you sure there isn't a problem elsewhere in your code?

Example

Upvotes: 51

jvecsei
jvecsei

Reputation: 1993

$("#id").remove(); should work.

Demo

Problems you might have with your code:

Maybe you aren't using the $(function() { }); around your code which tells jquery to wait until all html elements are loaded. ( short form for $(document).ready(function() { }) );

Upvotes: 2

Related Questions