Remove a link from HTML page before it loads with JAVASCRIPT

82 views Asked by At

HTML

I was sure I was on the right track, but for some reason the code of javascript doesn't work and doesn't remove the second link, can someone help me please?


<div class="p-4">
                    <h4 class="font-italic">Altro</h4>
                    <ol class="list-unstyled">
                        <li><a href="#">GitHub</a></li>
                        <li><a href="#">Twitter</a></li>
                        <li><a href="#">Facebook</a></li>
                    </ol>
                </div>

JAVASCRIPT


document.addEventListener("DOMContentLoaded", function RemoveLink() {
    // Seleziona il secondo link (Twitter) e rimuovilo
    var secondLink = document.querySelector('.list-unstyled li:nth-child(2) a');
    if (secondLink) {
       secondLink.remove()
    }
  });

1

There are 1 answers

1
54ka On BEST ANSWER

It's possible that the part of the page you're trying to intercept is loading with some delay and that's why it's not working. Try this solution. This code will keep trying until it succeeds in removing the element


document.addEventListener("DOMContentLoaded", function RemoveLink() {
  var intervalId = setInterval(function() {
    var secondLink = document.querySelector('.list-unstyled li:nth-child(2) a');
    if (secondLink) {
      secondLink.remove();
      clearInterval(intervalId); // спира повторението на опитите
    }
  }, 100);
});