Ans: To add attribute to an HTML element use attr() jquery method.

Following example demonstrate the attr() use.

<!--
Used basic html and bootstrap skeleton from the below link for style purpose which contains bootstrap.css,bootstrap.js,jquery.js
https://www.w3schools.com/bootstrap/bootstrap_get_started.asp
-->
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>How to add attributes to an HTML element in jQuery</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">        
    </head>
    <body>
        <div class="container" style="max-width:800px;margin:0 auto;margin-top:50px;">  
            <div>
                <h2 style="margin-bottom:50px;">Live Demo: How to add attributes to an HTML element in jQuery</h2>              
            </div>
            <div>
                <button type="button" class="add-href btn btn-success">Add Href</button>   
            </div>
            <div style="margin-top:20px;">
                <a class="web-link">Tutorialsmint.com</a>
            </div>
            <div style="margin-top:20px;" class="attr-added-msg"></div>
        </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <script>
            $(document).ready(function () {
                $(".add-href").click(function () {
                    $(".web-link").attr('href', 'http://www.tutorialsmint.com');
                    $(".attr-added-msg").html("Href attribute added to anchor tag, hover to see");
                });
            });
        </script>
    </body>
</html>


On clicking add href button it adds the href to the web-link class.

Written by
Check out this Author's contributed articles.
If you like Tutorialsmint and would like to contribute, you can also write an article using Write an Article. See your article appearing on the Tutorialsmint main page and help other programmers to enhance their knowledge.

Comments(0)

RECENT TUTORIALS
Wed Dec 26 • 08:00 AM GMT
Wed Dec 26 • 08:00 AM GMT
Wed Dec 26 • 08:00 AM GMT
Wed Dec 26 • 08:00 AM GMT
Wed Dec 26 • 08:00 AM GMT
Edit Post
Add Reply