Tony
Tony

Reputation: 12705

jQuery How to get the top-most container ID?

on my page, I have many html controls looking like that:

<span id="pic1" class="container">
    <span class="inner">
       <span class="img"></span>
       <span class="strip"></span>
       <span class="remove_the_main_container"></span>
    </span>
</span>

All I wanna do, is to remove (by using jQuery) the span with class="container" when user clicks at the span with class="remove_the_main_container". The problem is - How to get the ID of the top-most container inside which is placed that clicked span (class="remove_the_main_container") ?

Upvotes: 3

Views: 1966

Answers (4)

Ben
Ben

Reputation: 62444

This code is relative to which instance of remove_the_main_container so it requires no IDs or anything of that nature.

jQuery('.remove_the_main_container').bind('click', function (e) {
      jQuery(e.currentTarget).parents('.container').remove();
});

Upvotes: 2

Orbling
Orbling

Reputation: 20612

You should not need the ID to remove it.

$('.remove_the_main_container').click(function() {
    $(this).parents('.container').remove();
});

Upvotes: 5

user113716
user113716

Reputation: 322542

You can use jQuery's .closest() method to get to the first ancestor that matches the selector you give it.

$('.remove_the_main_container').click(function() {
    $(this).closest('.container').remove();
});

This way if there are other ancestors with the container class, they won't be affected.

Or if you meant that you wanted to remove that span, but not its content, then go to the .inner element, and use jQuery's unwrap() method.

$('.remove_the_main_container').click(function() {
    $(this).closest('.inner').unwrap();
});

Upvotes: 2

Alex
Alex

Reputation: 65972

If the topmost container always has a class of container, you could do something like this to get the id:

var id = $(".remove_the_main_container").parents(".container").attr("id");

But you don't need the id to remove the container. You could do something like this:

$(".remove_the_main_container").bind("click", function(eventObj) {
    $(this).parents(".container").remove();
});

Upvotes: 2

Related Questions