Thursday, 27 February 2014

How to make use of attributes in Jquery?

Jquery Attributes:

In this article, I will explain how make use of attributes using Jquery.

<p id="idAttr" title="Jquery Attributes" lang="en">Sample Text</p>

From the above element,

Tag Name is – p

Attributes are – id, lang, title

Set Attributes value:

The attr (name, value) method used to set the attributes using the passed values.

$('p').attr ("style", "background-color: Red");

Get Attributes value:

The attr () method used to fetch the value of the attribute

var values = $('p').attr("title");
alert(values);

Remove Attributes value:

The removeAttr () method used to remove the value of the attribute

$('p').removeAttr("style");
  
Example - Jquery Attributes:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="jquery-1.10.2.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#btnGet').click(function () {
                var values = $('p').attr("title");
                alert(values);
                return false;
            });
            $('#btnSetAttr').click(function () {
                $('p').attr("style", "background-color :Red");
                return false;
            });
            $('#btnRemoveAttr').click(function () {
                $('p').removeAttr("style");
                return false;
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <p id="idAttr" title="Jquery Attributes" lang="en">
            Jqueryjohn.com
        </p>
        <asp:Button ID="btnGet" runat="server" Text="Get Attribute Value" />
        <asp:Button ID="btnSetAttr" runat="server" Text="Set Attribute" />
        <asp:Button ID="btnRemoveAttr" runat="server" Text="Remove Attribute" />
    </div>
    </form>
</body>
</html>

No comments:

Post a Comment