JavaScript Code


How to remove all the links using JavaScript?


Tutorials using JS

Remove all the links

Given a HTML document, delete or remove all the link elements in the document using JavaScript.

Solution

To delete or remove all the link elements in the document using JavaScript, we can use Element.remove() property. Get all the link elements by tag name a, use a while loop to check if there are any more links, and if so delete the link by calling remove() method on the link element.

const links = document.getElementsByTagName("a");
while ( links.length > 0 ) {
    links[0].remove(); 
}

Program

In the following HTML code, we have a button element and two link elements. when user clicks on the button, we delete all the links in the document by calling remove() method on each of the link.

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Tutorial</h1>
<h2>Remove all links in document</h2>
<button id="myBtn">Click me</button><br>
<a href="/line-one/">Link 1</a><br>
<a href="/link-two/">Link 2</a>

<script>
//set onclick listener for #myBtn
document.getElementById("myBtn").addEventListener("click", function() {
    //get all the links in the document
    var links = document.getElementsByTagName("a");
    //iterate over the links and remove them
    while( links.length > 0 ) {
        links[0].remove();
    }
});
</script>

</body>
</html>

Copyright @2022