Tutorials using JS
Set all links to nofollow in the document
Given an HTML document with links, set all the link elements to no-follow links using JavaScript.
Solution
To set all the link elements in the document to no-follow links using JavaScript, set the rel
attribute of the links to nofollow
. Get all the link elements by tag name, use a for loop to iterate over the links, and for each link, set rel
attribute with "nofollow"
.
const links = document.getElementsByTagName("a");
for (let i = 0; i < links.length; i++) {
links[i].setAttribute("rel", "nofollow");
}
Program
In the following HTML code, we have a button element and two links. When user clicks on the button, we set all the links in the document to nofollow
links.
<!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 make them nofollow
for (let i = 0; i < links.length; i++) {
links[i].setAttribute("rel", "nofollow");
}
});
</script>
</body>
</html>