Friday, October 24, 2025
HomeLanguagesJavascriptHow to add attributes to an HTML element in jQuery?

How to add attributes to an HTML element in jQuery?

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.

Syntax:

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

Example:

HTML




<!DOCTYPE HTML>
<html>
  
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">  
    <script src="https://code.jquery.com/jquery-3.5.1.min.js">
    </script>
  
    <script>
        $(document).ready(function () {
            $("#add-attr").click(function () {
                $("#addAttr").attr("placeholder", "neveropen");
            });
        });
    </script>
</head>
  
<body style="text-align: center;">
    <h1 style="color: green;">
        neveropen
    </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:

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS