Shahid Karimi
Shahid Karimi

Reputation: 4357

jquery detecting and removing an element clicked

I have a hierachy of DIVs with classes associated but not IDs. How can I remove the item being clicked?

<div>
    <div class="minibox" onclick="remove_me()">Box1</div>
    <div class="minibox" onclick="remove_me()">Box1</div>
    <div class="minibox" onclick="remove_me()">Box1</div>
    <div class="minibox" onclick="remove_me()">Box1</div>
    <div class="minibox" onclick="remove_me()">Box1</div>
</div>
<script>
    function remove_me(){
    ///remove the clicked div
    }
</script>

Upvotes: 7

Views: 22041

Answers (8)

JaredMcAteer
JaredMcAteer

Reputation: 22536

$('.minibox').click(function() { $(this).remove(); });

Upvotes: 7

Martin Jespersen
Martin Jespersen

Reputation: 26183

Change

 <div class="minibox" onclick="remove_me()">Box1</div>

to

 <div class="minibox" onclick="remove_me(this)">Box1</div>

then use

<script>
 function remove_me(elm){
   $(elm).remove();
}
</script>

Upvotes: 5

gion_13
gion_13

Reputation: 41533

$('div .minibox').click(function(e){
    $(e.target).remove();
});

Upvotes: 20

balexandre
balexandre

Reputation: 75093

<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>
<div class="box">Box 4</div>
<div class="box">Box 5</div>

then you would use

$(".box").bind("click", function() {

  $(this).fadeOut(500, function() { 
    // now that the fade completed
    $(this).remove(); 
  });

});

Example in JSBIN

Upvotes: 1

meo
meo

Reputation: 31249

your html:

<div class="box">some content</div>
<div class="box">some content</div>
<div class="box">some content</div>
<div class="box">some content</div>
ect...

your jQuery

$(function(){ //make sure your DOM is ready
$("div.box").click(function(){ // bind click on every div that has the class box
  $(this).remove(); //remove the clicked element from the dom
});
});

Demo with fadeOut animation: http://jsfiddle.net/qJHyL/1/ (and fancy delete icon)

Upvotes: 1

Geoff Appleford
Geoff Appleford

Reputation: 18832

Inside the jQuery document.ready() event, you need to bind a click handler to the div's

$(document).ready(function() {
    $('.minibox').click(function(e){
        $(this).remove();
    });
});

Check out jQuery remove() and click().

The this inside the event handler refers to the element that was clicked on.

Upvotes: 2

Mark Coleman
Mark Coleman

Reputation: 40863

If you can use jQuery to register your event it is as easy as:

$(".minibox").click(function(){
   $(this).remove();
});

Code example on jsfiddle.

Upvotes: 1

Kon
Kon

Reputation: 27441

$(document).ready(function() {
  $('.minibox').click(function () {
    $(this).remove();
  });
});

Check out remove().

Upvotes: 1

Related Questions