How to Add Attribute to an HTML Element in jQuery?

Today, We want to share with you jquery add attribute.In this post we will show you jquery set input value, hear for jQuery – Set Content and Attributes we will give you demo and example for implement.In this post, we will learn about Get Content and Attributes using JavaScript jQuery with an example.

jQuery attr() Method

here you can learn jQuery Get Attributes, Set Attributes, Remove Attributes
Example 1:
Set the width attributes of an image:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("img").attr("width", "500");
  });
});
</script>
</head>
<body>

<img src="wwwpakainfocom.jpg" alt="Pulpit Rock" width="284" height="213"><br>

<button>Set the width attributes of the image</button>

</body>
</html>

Add and remove attributes with jquery

Example 2: jQuery Get Attributes Example

<html>
<head>
<title>jQuery get attributes example</title>
   <script type="text/javascript" 
   src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
   
   <script type="text/javascript" language="javascript">
   $(document).ready(function() {
      var title = $("em").attr("title");
	  alert(title);
      $("#yourcardid").text(title);
   });

   </script>
</head>
<body>
   <div>
      <em title=" my title attribute">jQuery get attributes</em>
      <p id="myid">getting my title attribute- success.</p>
      <div id="yourcardid"></div>
   </div>
</body>
</html>

jQuery Set Attribute

<html>
<head>
<title>jQuery set attributes example - www.pakainfo.com</title>
   <script type="text/javascript" 
   src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
   <script type="text/javascript" language="javascript">

   $(document).ready(function() {
      $("#pakainfo_logo").attr("alt", "Setting New pakainfo_logo");
   });

   </script>
</head>
<body>
   <div>
      <img id="pakainfo_logo" src="no-image.png" alt="old pakainfo_logo" />
   </div>
</body>
</html>

jQuery attribute methods

attr( properties ):

$( "img" ).attr({
  src: "/images/jquery.gif",
  title: "free download source code boook",
  alt: "Welcome To pakainfo"
});

removeAttr( name ):

$("table").removeAttr("border"); 

hasClass( class ):

$("p#pID").hasClass("isactive");

removeClass( class ):

$("p#pID").removeClass("isactive");

using text( ):

$(document).ready(function() {
     var title = $("em").attr("title");
     $("#yourcardid").text(title);
   });

I hope you get an idea about Set Content – text(), html(), and val().
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.