Matheus Siqueira Barros Matheus Siqueira Barros - 1 year ago 54
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");


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

Answer Source

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) {

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

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

$(".close").click(function() {

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download