[Solved] Remove parent without an id or class using JQuery

So I have some html that looks like the following:

<div class='something unknown' id='something_unknown_1'>
  <button onClick='removeParent(self)'>Remove me and my parent div</div>
</div>
<div class='something unknown' id='something_unknown_2'>
  <button onClick='removeParent(self)'>Remove me and my parent div</div>
</div>

…and so on. How exactly would I reference the button that fired the onClick without knowing the id of the button? I would like to eventually have my removeParent(self) method look like:

buttonThatWasClicked.parent().remove();
Enquirer: Atrus

||

Solution #1:

I would add a class to the buttons so the function does not get bound to every button on the page only the ones you would like it to.

<div class='something unknown' id='something unknown'>
  <button class="myClass">Remove me and my parent div</div>
</div>
<div class='something unknown' id='something unknown'>
  <button class="myClass" >Remove me and my parent div</div>
</div>

Then use the jquery class selector to bind a function that removes the parent.

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

Demo: http://jsfiddle.net/cXLqK/

Respondent: Kevin Bowersox

Solution #2:

You can use this to reference to the button that was clicked inside the click handler.

$("button").click(function(){
    removeParent($(this));
});

function removeParent(buttonThatWasClicked){
    buttonThatWasClicked.parent().remove();
}
Respondent: driangle

Solution #3:

If you have onclick on HTML nodes (i.e. not set via jQuery):

<div class='classA' id='idA'>
  <button onclick='removeParent(this)'>Remove me and my parent div</div>
</div>
<div class='classB' id='idB'>
  <button onclick='removeParent(this)'>Remove me and my parent div</div>
</div>

then this will work:

removeParent = function(e) {
    $(e).parent().remove();
}

Working example:

Respondent: icyrock.com

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published. Required fields are marked *

New ride at Perth's Adventure World a ‘swing on steroids’ - Australasian Leisure Management npp pharma the truth about anabolic steroid drugs and professional sports