I am trying to select a group of html elements and delete them from their parent elements. Currently, I get no exceptions when running the code, but the child elements remain on the page. In addition, running the same code in the developer console works without issue.
HTML:
<div id="one">
<img class="example">
</div>
<div id="two">
<img class="example">
</div>
<div id="three">
<img class="example">
</div>
JavaScript:
window.addEventListener("DOMContentLoaded", function () {
const getSelector = (input) => {
if (input.parentElement.id !== '') {
return input.parentElement.id;
}
else {
return getSelector(input.parentElement);
}
}
if (window.location.href.includes("language_edit")) {
document.querySelectorAll("img.example").forEach(e => {
let location = getSelector(e);
document.querySelector(`#${location}`).innerHTML = e.outerHTML.toString() + document.querySelector(`#${location}`).innerHTML;
document.querySelector(`#${location}`).firstChild.style.position = "relative";
e.parentElement.removeChild(e);
});
}
}, false);
If there is a better way to remove said elements, I would be happy to be told what it is, but I would also like to know if there is an issue with my code regardless.
EDIT: I have updated the code to include more of the original content for clarity.
3
Answers
Ultimately, I was able to solve the problem by using the
insertBefore
method to move the node rather than trying to delete it.try using this way
e.parentElement.children.removeChild(e);
When you set the
outerHTML
of the parent element, the<img>
element was removed from the DOM and itsparentElement
property becamenull
. You can verify that it is no longer attached to the document:Instead, you can
clone
the element, and useElement#before
orElement#after
to place it in the correct relative position.