I am trying to target the parent node, which is a div of a link tag(a) in my code, I have tried target.parentNode
but that does not work, maybe as I am using querySelectorAll?. My code so far is:
function remove() {
var target = document.querySelectorAll('a[data-type="data"]'), i;
for (i = 0; i < target.length; i++) {
if (target.length > 1) {
target[i].remove();
}
}
}
remove();
Html:
<div class="carousel-slide">
<a data-type="data" data-type="image">
<img class="img-responsive" src="./285-603.jpg">
</a>
</div>
Any idea's?
You could utilize for...of
to loop through all elements that were found, then call parentNode.remove()
on them:
function remove() {
var anchors = document.querySelectorAll("a[data-type='data']");
console.log("before", anchors.length);
// use `for...of` to iterate through all anchor tags
for (var anchor of anchors) {
// remove the parent node
anchor.parentNode.remove();
}
console.log(
"after",
document.querySelectorAll("a[data-type='data']").length
);
}
remove();
<div class="carousel-slide">
<a data-type="data" data-type="image">
<img
class="img-responsive"
draggable="false"
src="./285-602.jpg"
/>
</a>
</div>
<div class="carousel-slide">
<a data-type="data" data-type="image">
<img
class="img-responsive"
draggable="false"
src="./285-603.jpg"
/>
</a>
</div>
Reference:
You need to use parentNode.
const remove = () => {
const target = document.querySelectorAll('a[data-type="data"]');
for (let i = 0; i < target.length; i++) {
target[i].parentNode.remove();
}
};
remove();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With