How to add attribute using javascript

Follow us

There are different ways to add an attribute to the element. 

One way is to first create the attribute and then assign value to that attribute.

 Once it is created the attribute, you can set it to the element using setAttributeNode()

Here is an example: 
<!DOCTYPE html>
<html>
<head>
	<title>How to add the attr using javascript</title>
	<script type="text/javascript">
		window.onload = function() {
			var spanEle = document.getElementById('spanEle');

			var attribute = document.createAttribute('class'); //creates the attribute 
			attribute.value = 'new-class'; // assigning the value to the created attribute
			spanEle.setAttributeNode(attribute); 
		}
	</script>
</head>
<body>
	<div>
		<h4>Example : <span id="spanEle">How to add the attr using javascript : Using createAttribute & setAttributeNode </span></h4>
	</div>
</body>
</html>

Another way is to set the attribute using setAttribute(attribute, value) function. Include the attribute name and value.

Here is an example: 
<!DOCTYPE html>
<html>
<head>
	<title>How to add the attr using javascript</title>
	<script type="text/javascript">
		window.onload = function() {
			var linkEle = document.getElementById('link');
			linkEle.setAttribute('style', 'color:#sds1sfd;font-size:25px;');
		}
	</script>
</head>
<body>
	<div>
		<h4>Example : <a href="#" id="link">How to add the attr using javascript : Using setAttribute</a></h4>
	</div>
</body>
</html>