I manage to delete button with <li> element class li_listItem". But my aim is to on click delete <button> itself and also <li> element with it. For now I can only delete both elements only by clicking on it. Can you help me with it?
var ul = document.querySelector('#shopping_list__items');
function DeleteButtonOnclick(e) {
const trgt = e.target.closest('.deleteBtn, .li_listItem');
if (trgt) trgt.remove();
}
ul.addEventListener("click", DeleteButtonOnclick);
<ul id="shopping_list__items">
<div >
<li random="23">Notebook</li>
<button >Delete Button</button>
</div>
<div >
<li >Jello</li>
<button >Delete Button</button>
</div>
<div >
<li >Spinach</li>
<button >Delete Button</button>
</div>
<div >
<li >Rice</li>
<button >Delete Button</button>
</div>
<div >
<li >Birthday Cake</li>
<button >Delete Button</button>
</div>
<div >
<li >Candles</li>
<button >Delete Button</button>
</div>
</ul>
CodePudding user response:
Based on your html structure the simplest way is to delete the parent of the button. (I hope I didn't misunderstand what you want to do.)
$(".deleteBtn").click(function(){
$(this).parent().remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<ul id="shopping_list__items">
<div >
<li random="23">Notebook</li>
<button >Delete Button</button>
</div>
<div >
<li >Jello</li>
<button >Delete Button</button>
</div>
<div >
<li >Spinach</li>
<button >Delete Button</button>
</div>
<div >
<li >Rice</li>
<button >Delete Button</button>
</div>
<div >
<li >Birthday Cake</li>
<button >Delete Button</button>
</div>
<div >
<li >Candles</li>
<button >Delete Button</button>
</div>
</ul>
CodePudding user response:
I used this.parentNode.remove() method to delete both the <li> element and the <button> element inside the when the element with the deleteBtn class style is applied is clicked.
var elements = document.getElementsByClassName("deleteBtn");
var removeSelectedElement = function() {
this.parentNode.remove();
};
for (var i = 0; i < elements.length; i ) {
elements[i].addEventListener('click', removeSelectedElement, false);
}
<ul id="shopping_list__items">
<div >
<li random="23">Notebook</li>
<button >Delete Button</button>
</div>
<div >
<li >Jello</li>
<button >Delete Button</button>
</div>
<div >
<li >Spinach</li>
<button >Delete Button</button>
</div>
<div >
<li >Rice</li>
<button >Delete Button</button>
</div>
<div >
<li >Birthday Cake</li>
<button >Delete Button</button>
</div>
<div >
<li >Candles</li>
<button >Delete Button</button>
</div>
</ul>
