Matheus Siqueira Barros Matheus Siqueira Barros - 5 months ago 10
jQuery Question

Close button for div, accessing ID using Jquery

I want to create a close button for my divs. I have 3 divs, each one with a particular ID. So, my idea is to setting the CSS 'display' to 'none', accessing the id of each div.
The following example is not working.

Does someone have an idea why?

Java Script

function CloseDiv(element) {
var id = $(element).closest('div').attr('id')
alert(id) // It's returning the correct id
$(id).css("display", "none");
}


Html

<span id='close' onclick='CloseDiv(this)'>x</span>

Answer

You don't need to extract the id and make the div hide. You can have a direct selector and makes the div hide.

function CloseDiv(element) {
    $(element).closest('div').hide()
}

.hide() is equivalent to .css("display", "none");

You can also remove the inline function call with jquery like this,

$(".close").click(function() {
  $(this).closest("div").hide();
});

Note that I've used class instead of id selector, in case you have multiple elements

Comments