Mattia Del Franco
Mattia Del Franco

Reputation: 385

jQuery hide parents

I have the following HTML:

 <div class="windowtemplate movingwindow" style="display: block;">
    <div class="top">Attenzione <a href="#" onclick="closedialog();"><span class="closebutton"></span></a></div>
    <div class="body">
      <p>texthere</p>
      <a href="#" onclick="closedialog();"><span class="genericbutton">Close</span></a>
    </div>
    <div class="bottom"></div>
 </div>

I'm trying to hide this box (starting from div class="windowtemplate movingwindow") with jQuery with this code:

function closedialog() {
           $(this).parent("windowtemplate").hide();
    };

But this doesn't sort any effect, where i'm wrong? (I'm a newbie with jQuery, so, sorry if it's a really simple problem, but I can't find any solution!)

Upvotes: 0

Views: 67

Answers (3)

Rohan
Rohan

Reputation: 3334

First of all you missed the dot signifying a class and second parent() selector searches only level up in the tree, you need parents(). Use this code -

$('.genericbutton').on('click', function() {
    $(this).parents(".windowtemplate").hide();
}

Upvotes: 1

Mabedan
Mabedan

Reputation: 907

try this

  <a href="#" onclick="closedialog(this);"><span class="genericbutton">Close</span></a>

and this for your js

function closedialog(element) {
       $(element).closest(".windowtemplate").hide();
};

Upvotes: 1

Ram
Ram

Reputation: 144659

  1. this here doesn't refer to the clicked element.
  2. The selector is wrong, missing . for the class selector.
  3. .parent() doesn't select the grandparent elements, you should use .closest() instead.
  4. You should avoid using attribute event handlers.

    $('.genericbutton').on('click', function() {
         $(this).closest('.windowtemplate').hide();
    });
    

If the .windowtemplate is generated dynamically you should delegate the event, if you are using jQuery 1.7+ you can use the .on() method:

$(document).on('click', '.genericbutton', function() {
   $(this).closest('.windowtemplate').hide();
});

Upvotes: 1

Related Questions