jQuery

How to add attribute to an HTML element in jQuery

In this tutorial, we are going to see how to add attribute to an HTML element in jQuery. You can use the attr() method of jQuery to add attributes to an HTML element.

In the following example, when you click on the “Select checkbox” button, it dynamically adds the “checked” attribute to the checkbox.
 

How to add attribute to an HTML element in jQuery
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>How to add attribute to an HTML element</title>
		<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
		<script type="text/javascript">
			$(document).ready(function(){
				$(".ajouter-attr").click(function(){            
					$('input[type="checkbox"]').attr("checked", "checked");
				});
			});
		</script> 
	</head>
	<body>
		<button type="button" class="ajouter-attr">Check the checkbox</button>
		<input type="checkbox"> 
	</body>
</html>
Result
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *