The following code shows an Example of hasAttribute() and setAttribute() Methods in JavaScript. While the hasAttribute() determines whether a specific attribute is used in a tag. On the other hand, the setAttribute() method assigns a value to a particular attribute.
Programmingempire
Illustrating an Example of hasAttribute() and setAttribute() Methods in JavaScript
The following HTML document contains two anchor elements. Also, they have the target attribute with “_self” value. Further, there is a button that has an event handler method f1() for the click event. When a user clicks on the button the function f1() executes. At first, the function finds out whether the hyperlinks have a target attribute using the hasAttribute() method. In case it is there, the setAttribute() method changes the value of the target attribute to “_blank”.
Therefore, when a user opens the document in a browser and clicks on the hyperlinks, it will open the page in the same tab. When a user clicks on the button and then clicks on the hyperlink the pages will be opened in a separate tab.
<html>
<head>
<title>hasAttribute Method Demo</title>
<script>
function f1()
{
var v1=document.getElementById("d2");
var x1=document.getElementsByTagName("a");
for(i=0;i<x1.length;i=i+1)
{
if(x1[i].hasAttribute("target"))
{
x1[i].setAttribute("target", "_blank");
}
}
str="Clicking on above URLs will now open them in a new tab";
str1=v1.innerHTML;
str1+="<br/>"+str;
v1.style.width='400px';
v1.style.display='block';
v1.innerHTML=str1;
}
</script>
<style>
.c1{
border: 4px solid #33ff99;
border-radius: 10px;
background-color: #5566aa;
color: #aaffff;
font-size: 20px;
text-align: center;
margin:5px;
padding: 10px;
}
.a1{
margin: 50px;
}
.c2{
background-color: #ddeeff;
color: #ff5566;
font-size: 25px;
text-align: left;
margin:40px;
padding: 5px;
width: 600px;
}
</style>
</head>
<body>
<div id="d1" class="c2"><br/><br/>
Example of hasAttribute() Method<br/>
Clicking on these URLs will now open them in the current tab
<br/><br/>
<a class="a1" href="http:\\programmingempire.com" target="_self">Programmingempire</a>
<a class="a1" href="http:\\princites.com" target="_self">Princites</a>
<br/><br/>
<button id="b7" class="c1" onclick="f1()">Set Target Attribute</button>
<br/><br/>
<div class="c2" id="d2" style="display:none;"></div>
</div>
</body>
</html>
Output
Further Reading
Evolution of JavaScript from ES1 to ES2020
Introduction to HTML DOM Methods in JavaScript