简体   繁体   中英

Remove div from DOM with Jquery

I´m trying to remove the "closest" div with a class of: flak
I have tried using "parent" but it will remove a higher div.
I need to remove the div with a class of ".flak" and all it´s children.

HTML

<div class="well" id="flakDiv"> 
  <span id='deleteFlak' class='pull-right'>x</span>
  <div class="flak nopadding" id="77">
  <div class="flakSideUp nopadding"></div>
  <div class="flakMiddle">Flak <b><span>88<span></b><p>88</p></div>
  <div class="flakSideDown nopadding"></div>
</div><br>

Js

//Flak HTML setup
var flak = $('<div class="flak nopadding" id="'+flakId+'"><div class="flakSideUp nopadding"></div><div class="flakMiddle">Flak <b><span>'+flakNr+'</span></b><p>'+ chosenObjNr +'</p></div><div class="flakSideDown nopadding"></div></div><br>');

//Delete flak
$('#deleteFlak').on('click', function(){
    $(this).closest('.flak').remove();
});

You need to use $.fn.next() ,as it looks from immediately following sibling. the $.fn.closest() method traverses up through its ancestors in the DOM tree including itself.

Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.

Use

//Delete flak
$('#deleteFlak').on('click', function(){
    $(this).next('.flak').remove();
});

Try the FIDDLE .

Following code finds the class flak under the parent DIV of span #deleteFlak .

Javascript code :

$(function(){
    $('#deleteFlak').on('click', function(){
        alert('close');
        $(this).closest('div').find('.flak').remove();
    });
});

Hpe this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM