How do I remove the parent element and all the respective nodes using plain JavaScript? I\'m not using jQuery or any other library. In other words, I have an element and whe
Simple function to do this with ES6:
const removeImgWrap = () => {
const wrappedImgs = [...document.querySelectorAll('p img')];
wrappedImgs.forEach(w => w.parentElement.style.marginBottom = 0);
};
I know it's a little too late, but someone else might find it useful.
Just wrote a function for that.
Change this:
onClick="delete_row(this)"
To this:
onClick="removeParents(this, document.getElementById('id'))"
function removeParents(e, root) {
root = root ? root : document.body;
var p = e.parentNode;
while(root != p){
e = p;
p = e.parentNode;
}
root.removeChild(e);
}
http://jsfiddle.net/emg0xcre/
I know I am too late but I still can't see more accurate answer.
So here you go.
You can specify it even more. Instead of parentElement.parentElement
you can do something like this.
static delete_row(element) {
element.closest("tr").remove();
}
The other preferred way of handling such scenario would be event propagation instead of adding onclick
to html element.
e.g
HTML
<tr id='id'>
<td>Mohit</td>
<td>23</td>
<td >
<span class="edit">Edit</span> |
<span class="delete">Delete</span>
</td>
<td style="display:none;"><span onClick="save(this)">Save</span></td>
</tr>
JavaScript
document.querySelector("#id").addEventListener("click", (e) => {
UI.handleEvents(e.target);
});
static handleEvents(el){
if (el.classList.contains("delete")) {
el.closest("tr").remove();
}
if (el.classList.contains("edit")) {
// do something else
}
}