Skip to main content

How To Get HTML Element Attribute Value in jQuery

Submitted by admin on Thu, 01/06/2022 - 08:06
jquery-element-attribute-value

In this jQuery tutorial we will learn how to get and print attribute value of any html element.

There are large number of attributes in HTML like name, lang, title, alt etc.

In this tutorial, we will get and print the value of name attribute of input fields when the input field is focused.

Step 1: HTML

Let's create few input fields and a region to display the value of name attribute.


<label>Name: </label><input type="text" name="name" value="">
<label>Email: </label><input type="text" name="email" value="">
<br /><br />
<div class="focus-message"></div>

Step 2: jQuery

jQuery attr() method is used to get the value of any HTML attribute.

Syntax


$('selector').attr('attribute name');

Use below jQuery code to get and print the value of name attribute in a div of class name focus-message


<script>
$(document).ready(function(){
  $('input[type="text"]').focus(function(){
    var focus_field_name = $(this).attr("name");
    $('.focus-message').fadeIn().text(focus_field_name);
  })
})
</script>

Full Code

Below is full code.


<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Get Attribute Value in jQuery</title>
    <script src="//code.jquery.com/jquery-3.4.1.min.js"></script>
    <script>
    $(document).ready(function(){
      $('input[type="text"]').focus(function(){
        var focus_field_name = $(this).attr("name");
        $('.focus-message').fadeIn().text(focus_field_name);
      })
    })
    </script>
    <style>
    .focus-message {
      display: none;
      padding: 10px;
      background: yellow;
    }
    </style>
  </head>
  <body>
  <label>Name: </label><input type="text" name="name" value="">
  <label>Email: </label><input type="text" name="email" value="">
  <br /><br />
  <div class="focus-message"></div>
  </body>


Demo

Print Element Attribute Value in jQuery

Category

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.