Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
149
rated 0 times [  153] [ 4]  / answers: 1 / hits: 17453  / 9 Years ago, sun, june 28, 2015, 12:00:00

I am trying to delete the div on button click but the problem that I need the button to delete the div that it contain to without passing the id of the div to the delete button



so this code at the end should be able to delete the div without passing the id of the div instead it will depend on passing this reference



<!doctype html>
<html>

<head>
<script src=http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js></script>
<script>
$(document).ready(function() {
$(document).on('mouseenter', '#divbutton', function() {
$(this).find(:button).show();
}).on('mouseleave', '#divbutton', function() {
$(this).find(:button).hide();
});
});
</script>

<style>
#divbutton {
height: 100px;
background: #0000ff;
}

#divbutton2 {
height: 100px;
background: #0000ff;
}

#divbutton3 {
height: 100px;
background: #0000ff;
}
</style>
</head>
<body>
<div id=divbutton>
<button type=button style=display: none; id=i onclick=document.body.removeChild(document.getElementById('divbutton'))>Hello</button>
</div>

<div id=divbutton2>
<button type=button style=display: none; id=i onclick=document.body.removeChild(document.getElementById('divbutton2'))>Hello </button>
</div>

<div id=divbutton3>
<button type=button style=display: none; id=i onclick=document.body.removeChild(document.getElementById('divbutton3'))>Hello </button>
</div>
</body>

</html>

More From » jquery

 Answers
8

If you want to know how to use this reference to get hold of the parent element to pass it to removeChild, then it's quite easy, just use parentNode:



<div class=divbutton>
<button type=button style=display: none; id=i onclick=document.body.removeChild(this.parentNode)>Hello</button>
</div>


However, since you are using jQuery it makes sense to make use of it's power:



$(document).on('mouseenter', '.divbutton', function () {
$(this).find(:button).show();
}).on('mouseleave', '.divbutton', function () {
$(this).find(:button).hide();
}).on('click', ':button', function() {
$(this).parent().remove();
});


I also changed ids #divbuttonX to class name .divbutton, CSS becomes simpler in this case too.



Demo: http://jsfiddle.net/5qfjo0c7/


[#66005] Friday, June 26, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brodyfrancisi

Total Points: 1
Total Questions: 102
Total Answers: 89

Location: Marshall Islands
Member since Mon, May 31, 2021
3 Years ago
brodyfrancisi questions
;