JQuery How to get the topmost container id?

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

<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 want to do is delete (using jQuery) spans class="container"when the user clicks on spanwith class="remove_the_main_container". The problem is that - How to get the identifier of the topmost container inside which this span ( class="remove_the_main_container") click is located ?

+3
source share
4 answers

You can use the jQuery method.closest() to get to the first ancestor that matches the selector of your choice.

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

That way, if there are other ancestors with the class container, they will not be affected.

, span, , .inner jQuery unwrap().

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

, .

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

If the topmost container always has a class container, you can do something like this to get the identifier:

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

But to remove the container you do not need an identifier. You can do something like this:

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

This code refers to which instance remove_the_main_container, so it does not require identifiers or anything like that.

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

Source: https://habr.com/ru/post/1775721/


All Articles