Tutorials using JS
Remove link element from document
Given a link element in the document, remove the link element from the document using JavaScript.
Solution
To remove a link element from the document using JavaScript, select the link element by the required selection criteria, and use element’s remove()
method. Call the remove()
method on the link element as shown in the following.
const link = document.getElementById("link1");
link.remove();
Once removed, the link is not present in the document.
Program
In the following HTML code, we have a button element and a link element. When user clicks on the button, we remove (delete) the link element.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Tutorial</h1>
<h2>Remove link element from Document</h2>
<button id="myBtn">Click me</button><br>
<a id="link1" href="/some-link/">Some link</a><br>
<script>
//set onclick listener for #myBtn
document.getElementById("myBtn").addEventListener("click", function() {
//get the link
const link = document.getElementById("link1");
//remove the link
link.remove();
});
</script>
</body>
</html>