How to use jQuery to get the value of HTML attribute of elements?

To get the value of HTML attributes in jQuery, you can use different methods depending on what you're trying to retrieve. The val() method is used to get the current value of form elements like input fields, textareas, and select boxes. For other HTML attributes like id, class, or src, use the attr() method instead.

Getting Form Element Values

The val() method retrieves the value attribute of form elements. Here's how to use it ?

Example

You can try to run the following code to learn how to use jQuery to get the value of HTML attribute of elements ?

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
      $(document).ready(function() {
        $("#buttonSet").click(function () {
          $("#buttonGet").removeAttr('disabled');
        });

        $("#buttonGet").click(function () {
          $("#result").html(
            $("#txtBox").val() + "<br/>" +
            $("input:radio[name=rd]:checked").val()
          );
        });
      });
    </script>
  </head>
  <body>
    Name <br />
    <input id="txtBox" type="text" />
    <br /><br />
    Gender <br />
    <input type="radio" name="rd" value="male"/> Male
    <input type="radio" name="rd" value="female"/> Female
    <br /><br />
    <input id="buttonSet" type="button" value="Set Values" />
    <input id="buttonGet" type="button" value="Get Values" disabled="disabled" />
    <p id="result"></p>
  </body>
</html>

Getting Other HTML Attributes

For non-form attributes like id, class, href, or custom data attributes, use the attr() method ?

// Get the id attribute
var elementId = $("#myElement").attr("id");

// Get the class attribute  
var elementClass = $("#myElement").attr("class");

// Get a custom data attribute
var customData = $("#myElement").attr("data-custom");

Conclusion

Use val() to get form element values and attr() to retrieve other HTML attributes. Both methods are essential for accessing element properties in jQuery.

Updated on: 2026-03-13T18:12:57+05:30

331 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements