1
<div class="chatbox-window">
    <div class="chatbox-title">
        <div class="chatbox-username"></div><div class="chatbox-close"><span class="chatbox-close-button"></span></div>
    </div>
    <div class="chatbox-content"><div class="chatbox-msg"></div></div>
    <div id="chatbox-posting"></div>
</div>

    $(".chatbox-close-button").click(function(){
        $(this).parent(".chatbox-close").parent(".chatbox-title").parent(".chatbox-window").remove();
    });

Below, i use:

$(this).parent(".chatbox-close").parent(".chatbox-title").parent(".chatbox-window") to get the ".chatbox-window"

But:

Are there shorter ways to get the .chatbox-window

Ps. In case of not changing the HTML code.

Devang Rathod
  • 6,650
  • 2
  • 23
  • 32
InOrderToLive
  • 186
  • 1
  • 1
  • 9

4 Answers4

1

use parents()

Official Document

Description: Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.

$(this).parents(".chatbox-window").remove();
Dipesh Parmar
  • 27,090
  • 8
  • 61
  • 90
  • I think this will work if change span -> div. Any way, thanks :) – InOrderToLive Mar 14 '13 at 05:21
  • @InOrderToLive it does not matter as long as you just define class name..if you specify .parents("div.chatbox-window") then it will look for div with having class that you have declared.. – Dipesh Parmar Mar 14 '13 at 05:27
0

Use .closest()

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

$('.chatbox-close-button').click(function(){
    $(this).closest('.chatbox-window').remove();
});

Demo: Fiddel

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0
 $(this).parents('div:eq(0)').remove();
sasi
  • 4,192
  • 4
  • 28
  • 47
0

You can use jquery closest(). Documentation here

$(this).closest('.chatbox-window').remove()
uchamp
  • 2,492
  • 1
  • 20
  • 31