Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to add attributes to an HTML element in jQuery?

  • Last Updated : 09 Feb, 2021

Given an HTML document containing some elements and the task is to add the attributes to the HTML elements.

Approach: Given an HTML document containing <label>, <input> and <button> elements. The <input> element contains the type and id attribute. When user click on the button, the jQuery function is called. We use $(selector).attr() method to add the attributes. Here, we are adding the placeholder attribute to the input field.

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

Syntax:

$("#add-attr").click(function () {
    $("#addAttr").attr("placeholder", "GeeksforGeeks");
});

Example:

HTML




<!DOCTYPE HTML>
<html>
  
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">  
    </script>
  
    <script>
        $(document).ready(function () {
            $("#add-attr").click(function () {
                $("#addAttr").attr("placeholder", "GeeksforGeeks");
            });
        });
    </script>
</head>
  
<body style="text-align: center;">
    <h1 style="color: green;">
        GeeksforGeeks
    </h1>
  
    <h4>
        How to add attributes to an HTML element in jQuery?
    </h4>
  
    <label for="addAttr"></label>
    <input type="text" id="addAttr">
  
      <button id="add-attr">Add Placeholder Attribute</button>
</body>
  
</html>

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :