The attr() is a method of Jquery. It is used to set an attribute and value on the Html tag. This method will replace the attribute' value If the HTML element has the attribute from the same name, you are imposing by the Jquery attr() method otherwise It will add.
attr() method syntax Jquery's attr() method example Add style attribute in Jquery Add multiple attributes in Jquery |
For example, if an element already has align
attribute then attr() function will replace its value with the new value from the attr() method's second parameter.
And when an element has no attribute from the same name defined in attr(), then this method will set that attribute and value you set in attr()'s parameter.
Jquery's attr() method syntax
The name of the attribute and its value must be separated by a comma and both must be in separate double-quotes. See syntax below-
$(selector).attr("align","center");
Juqery's attr() method example
<!DOCTYPE html>
<html>
<head>
<title>Add attribute in Jquery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<h1 align="center">This is H1 tag</h1>
<button id="btn">Add attribute</button>
<script>
$(document).ready(function(){
$("#btn").click(function(){
$("body").attr("bgcolor","red");
});
});
</script>
</body>
</html>
Add "style" attribute (Inline CSS) in Jquery
<!DOCTYPE html>
<html>
<head>
<title>Add STYLE attribute in Jquery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<h1 id="heading">This is H1 tag</h1>
<button id="btn">Add attribute</button>
<script>
$(document).ready(function(){
$("#btn").click(function(){
$("#heading").attr("style","color:red;font-size:50px;");
});
});
</script>
</body>
</html>
Add multiple attributes in Jquery
To add multiple attributes in Jquery, you need to add Curly braces in attr() methods parenthesis like this:- $(selector).attr({});
Now, property and its value will be separated by a colon ( : ).
And two different attributes will be separated by a comma ( , ).
Syntax:-
$("#heading").attr({
"align":"center",
"style":"color:red;"
});
Add multiple attributes example-
<!DOCTYPE html>
<html>
<head>
<title>Add STYLE attribute in Jquery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<h1 id="heading">This is H1 tag</h1>
<button id="btn">Add attribute</button>
<script>
$(document).ready(function(){
$("#btn").click(function(){
$("#heading").attr({"align":"center","style":"color:red;"});
});
});
</script>
</body>
</html>
Similarly, you are free to add a class, an id, custom attributes and attributes whichever you want to add to your Html element.
If you want to add a blank (with no value) attribute then make its value empty like this $(selector).attr("align","");
Publish A Comment