Javascript on div id click close parent div and child div?
I have a post div class like:
<div class="message_box_prompt">
<div class="boxclose" id="boxclose" onclick="this.parentNode.parentNode.removeChild(this.parentNode);">✖</div>
This is a message
</div>;
If my user clicks on my div boxclose
, this closes the message box message_box_prompt
and also removes the div boxclose
.
onclick="this.parentNode.parentNode.removeChild(this.parentNode);
My problem is that I have multiple instances of my div class message_box_prompt
displayed on the page:
Occurrence 1
<div class="message_box_prompt">
<div class="boxclose" id="boxclose" onclick="this.parentNode.parentNode.removeChild(this.parentNode);">✖</div>
This is a message
</div>;
Occurrence 2
<div class="message_box_prompt">
<div class="boxclose" id="boxclose" onclick="this.parentNode.parentNode.removeChild(this.parentNode);">✖</div>
This is a message
</div>;
Occurrence 3
<div class="message_box_prompt">
<div class="boxclose" id="boxclose" onclick="this.parentNode.parentNode.removeChild(this.parentNode);">✖</div>
This is a message
</div>;
I only need the one that the user clicks to close. I don't want it to close any of the others, instead for now, if my user clicks on one message_box_prompt
div to close it, they all close.
Can anyone show me the best way to do this so that I can do as I want? thank
source to share
If you are using JQuery this might help
Parent : https://api.jquery.com/parent/ (if you need it)
Hide : http://api.jquery.com/hide/
I would suggest, just like the comment, to give each child a unique ID, this would make the following code so easy to use.
$("#uniqueID").hide();
Or pure Javascript
document.getElementById('uniqueID').style.display = 'none';
source to share
Your HTML is incorrect, you have redundant
</div>';
and for some reason a '; at the other end of it. You are also repeating the same identifier, but you are not part of the problem because you are using this keyword. I dont know why you have the problem when they all close, it looks like I am working fine in the jsfiddle that I put it in.
<div class="message_box_prompt">
<div
class="boxclose"
onclick="this.parentNode.remove();"
>✖</div>
<p>Message 1</p>
</div>
<div class="message_box_prompt">
<div
class="boxclose"
onclick="this.parentNode.remove();"
>✖</div>
<p>Message 2</p>
</div>
<div class="message_box_prompt">
<div
class="boxclose"
onclick="this.parentNode.remove();"
>✖</div>
<p>Message 3</p>
</div>
source to share
How about this:
<div class="message_box_prompt">
<div class="boxclose" id="boxclose" onclick="this.style.visibility='hidden'">✖This is a message</div>
<div class="boxclose" id="boxclose" onclick="this.style.visibility='hidden'">✖This is a message</div>
<div class="boxclose" id="boxclose" onclick="this.style.visibility='hidden'">✖This is a message</div>
</div>
source to share