How to add an attribute to the HTML element using jQuery

Follow us

As jQuery described “write less do more”, it really proves it. jQuery makes it very easy to add an attribute to the element.

In a less code, you can do more. For instance, attr(name,value) method is used to bind the attribute-value. 

Now let’s look into an example: In the below example, we have used ID as a selector to bind it. 

<!DOCTYPE html>
<html>
<head>
	<title>How to add the attr using jquery</title>
	<head>
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
	</head>
	<script type="text/javascript">
		function addAttribute(){
			$('#ele').attr('style','color:#467fcf; font-size: 20px');
		}
	</script>
</head>
<body>
	<div>
		<p id="ele">Adding the attribute to the HTML element using jquery</p>
		<button type="button" onclick="addAttribute()"> Add Style attribute </button>
	</div>
</body>
</html>