Tutorials using JS
Hide all the links in page in JavaScript
In this tutorial, you will learn how to hide all the link elements in the document using JavaScript.
Solution
To hide all the link elements in the document using JavaScript, we can use Element.style.display
CSS property. Get all the link elements by tag name, use a for loop to iterate over the links, and for each link, set style.display
CSS property with "none"
.
const links = document.getElementsByTagName("a");
for (let i = 0; i < links.length; i++) {
links[i].style.display = "none";
}
Program
1. In the following HTML code, we have a button element and two links. When user clicks on the button, we hide all the links in the document by setting each of the link’s style.display
to none
.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Tutorial</h1>
<h2>Hide all links in document</h2>
<button id="myBtn">Click me</button><br>
<a href="https://javascriptcode.org/">JavaScript Tutorials 1</a><br>
<a href="https://javascriptcode.org/">JavaScript Tutorials 2</a>
<script>
//set onclick listener for #myBtn
document.getElementById("myBtn").addEventListener("click", function() {
//get all the links in the document
const links = document.getElementsByTagName("a");
//iterate over the links and hide them
for (let i = 0; i < links.length; i++) {
links[i].style.display = "none";
}
});
</script>
</body>
</html>