Javascript Set Custom Attribute To Element

Apr 17, 2021 . Admin

Hello Friends,

Now let's see example of how to custom attribute to element in javascript. Here you will learn how to use javascript custom attribute to element. We will use how to set custom attribute to element in javascript. This is a short guide on set custom attribute to element. Let's get started with how to set custom attribute to element in javascript.

Here i will give you many example how you can set custom attribute to element in javascript.

Example: 1
<!DOCTYPE html>
<html>
	<head>
		<title>Javascript - How to set custom attribute to element?-MyWebtuts.com</title>
		<style>
			.studclass {
			  	color: red;
			}
		</style>
	</head>
	<body>

		<h1>Javascript Example</h1>

		<p>Click the button to create a "class" attribute with the value "studclass" and insert it to the H1 element above.</p>

		<button onclick="testFunction()">Test</button>

		<script>

			function testFunction() {
			  	var h1 = document.getElementsByTagName("H1")[0];
			  	var att = document.createAttribute("class");
			  	att.value = "studclass";
			  	h1.setAttributeNode(att);
			}

		</script>
		
	</body>
</html>
Output: 1
Javascript Example - red colour
Example: 2
<!DOCTYPE html>
<html>
	<head>
		<title>Javascript - How to set custom attribute to element?-MyWebtuts.com</title>	
	</head>
	<body>

		<a id="test">A Link: Go to MyWebtuts.com</a>

		<p>Click the button to create a "class" attribute with the value "www.MyWebtuts.com" and insert it to the a element above.</p>

		<button onclick="studFunction()">GO to Link</button>

		<script>

			function studFunction() {
				var anchor = document.getElementById("test");
				var att = document.createAttribute("href");
				att.value = "https://www.MyWebtuts.com";
				anchor.setAttributeNode(att);
			}
			
		</script>

	</body>
</html>
Output: 2
A Link: Go to MyWebtuts.com

It will help you....

#Javascript