LearnFast.Ninja

jQuery attr

The attr function enable to add attributes to elements, to understand it let's look at the next example, add the src attribute to img element. The main idea: $("#" + Id).attr("src",url);

Step 1: create custom img element

<img width="400" id="img_ID" onclick="add_src_attr('img_ID','image.png');" />


Step 2: create javascript function, call it add_src_attr

function add_src_attr(Id, url) {

    $("#" + Id).attr("src", url);

}


The main idea:

$("#" + Id).attr("src", url);


Complete code:

<html>

<head>

    <title>jQuery attr</title>

    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.min.js"></script>

    <script type="text/javascript">

        function add_src_attr(Id, url) {

            $("#" + Id).attr("src", url);

        }

    </script>

</head>

<body>

    <img width="400" id="img_ID"

        onclick="add_src_attr('img_ID','image.png');" />

</body>

</html>


Tags

jquery

attr attribute