jQuery Set Attribute and Get Attribute

jQuery Set Attribute and Get Attribute

jQuery Set Attribute

The jQuery attr() method is used to set or return attributes and values of the selected elements.

Syntax of jQuery set attribute.

$(selector).attr(attribute, value);

Example of jQuery set attribute.

<!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(){
      $("#web-tuts").attr("href", "https://web-tuts.com/category/jquery/");
   });
  });
</script>
</head>
<body>

<p><a href="https://web-tuts.com" id="web-tuts">web-tuts.com</a></p>

<button>Change href Value</button>

<p>Mouse over the link (or click on it) to see that the value of the href attribute has changed.</p>

</body>
</html>

jQuery Get Attribute

The jQuery attr() method is used to get attribute values.

Read Also :  Enter Only Number in Textbox using jQuery

Syntax of jQuery get attribute.

$(selector).attr(attribute, value);

Example of jQuery Get Attribute.

<!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(){
    alert($("#web-tuts").attr("href"));
   });
  });
</script>
</head>
<body>
  <p><a href="https://web-tuts.com" id="web-tuts">web-tuts.com/</a></p>
  <button>Show href Value</button>
</body>
</html>