-->

22 April 2021

jQuery Reading Attribute Values

  Asp.Net CS By Example       22 April 2021
jQuery Reading Attribute Values

 In this post, we are learning about jQuery Reading Attribute Values. jQuery lets we examine the values of attributes with the attr() function. For example, if we have two <img> elements in a page and want to read the alt attribute of the first <img> element, we can pass the name of the attribute to be read to the jQuery attr() function.


 $("img:first").attr("alt") 

 In addition, jQuery provides a way of getting the elements from a jQuery wrapped set. We might think that this would work.


 $("img")[0].attr("alt") 

 However, the [0] syntax returns a browser element, not a jQuery wrapped element, so the attr( ) function will not work here. An easy way of getting elements from a wrapped set is to use the jQuery slice( ) function; slice(m, n) returns the elements m to n-1 of a wrapped set, so we can get the first element of a wrapped set like this.


 $("img").slice(0, 1).attr("alt") 

 Below code example puts for see above Reading Attribute Values working.

jqscript.html
<html>
<head>
    <title>
        Reading an alt attribute
    </title>
    <script src="jquery-latest.js"></script>
    <script type="text/javascript">
        function getAlt() {
            alert($("img").slice(0,
            1).attr("alt"));
        }
    </script>
</head>
<body>
    <h1>Reading an alt attribute</h1>
    <img src="../../img/jquery-logo.png"
         alt="This is an image of jQuery logo." />
    <img src="../../img/jquery-logo.png"
         alt="This is also an image of jQuery logo." />
    <br>
    <form>
        <input type="button"
               value="Get alt attribute"
               onclick="getAlt( )"
        </input>
    </form>
</body>
</html>


Output:

logoblog

Thanks for reading jQuery Reading Attribute Values

Previous
« Prev Post

No comments:

Post a Comment

Please do not enter any spam link in the comment box.