0

How to close alert message parent div using javascript?

Problem is parent div is closing but i need to close above parent div.

Here is my code:

$(".msg-error .btn-close").click(function(){$(this).parent().hide();});
.msg-error {
    background:#ff0000;
    color:#fff;
    padding:10px;
    margin-bottom:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="mainalert">

<div class="msg-error">
    <div class"container">
    First error message <a class="btn-close">Close</a>
    </div>
</div>

<div class="msg-error">
    <div class"container">
    Second error message <a class="btn-close">Close</a>
    </div>
</div>

</div>

5 Answers 5

2

You can use .closest() to specify the closest parent you want to achieve by using a selector.

$(".msg-error .btn-close").click(function() {
  $(this).closest('.msg-error').hide();
});

With this function you can even change your HTML structure without having to edit your JavaScript code to deal with multiple level of .parent() calls, provided that you continue using the same CSS class for the selector.

FIDDLE: http://jsfiddle.net/8b7zt1g7/5/

Sign up to request clarification or add additional context in comments.

Comments

1
$(".msg-error .btn-close").click(function(){$(this).parent().parent().hide();});

http://jsfiddle.net/8b7zt1g7/4/

Or, little fancier:

$(".msg-error .btn-close").click(function(){$(this).closest('.msg-error').hide();});

Comments

0

You can chain .parent() calls together. Try:

$(".msg-error .btn-close").click(function(){$(this).parent().parent().hide();});

Comments

0

you can try this way, by searching for that main parent div

you can use closest() or parents(), first option will return first match and seconds will return all matches, your choice

$(".msg-error .btn-close").click(function() {
    $(this).parents(".msg-error").hide();
});

or going the parent twice

$(".msg-error .btn-close").click(function() {
    $(this).parent().parent().hide();
});

Comments

0

Remove parent div without jquery

<div class="msg-error">
    <div class"container">
    Second error message <a class="btn-close" onclick='Close()'>Close</a>
    </div>
</div>
<script>
function Close(){
document.getElementsByClassName('msg-error').innerHtml='';
}
<script>

1 Comment

this is not hide, this remove, also getElementsByClassName return live HTMLCollection so it don't have innerHtml property

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.