• Jquery for Beginners – Get and Set Attributes of elements

    Posted on July 18, 2012 by in Jquery, Other Programming

    If you are new to Jquery please go through Introduction to JQuery and Jquery Selectors. This article explains how to get and set attribute values of DOM elements. As in previous article let us use the HTML below and try to manipulate it’s content

                        <form id="frm" name="frm" action="#">
                        <fieldset>
                            <legend>Event Details:</legend>
                            <div class="formhearder">
                                <p>Jquery Selector</p>
                            </div>
                            <div class="error">
                            </div>
                            <div class="row">
                                <label>
                                    Title:</label>
                                <input type="text" id="txtTitle" name="txtTitle" style="width: 450px;" />
                                <div class="clr">
                                </div>
                            </div>
                            <div class="row">
                                <label>
                                    Occurance Type:</label>
                                <input type="radio" name="rdoRecur" id="rdoRecurNo" value="0" checked="checked" />One
                                Time Event &nbsp;
                                <input type="radio" name="rdoRecur" id="rdoRecurYes" value="1" />Recurring Event
                                <div class="clr">
                                </div>
                            </div>
                            <div class="row">
                                <label>
                                    Start Date:</label>
                                <input type="text" id="txtStartDate" name="txtStartDate" />
                                <div class="clr">
                                </div>
                            </div>
                            <div class="row">
                                <label>
                                    End Date:</label>
                                <input type="text" id="txtEndDate" name="txtEndDate" />
                                <div class="clr">
                                </div>
                            </div>
                            <div style="height: 10px;">
                            </div>
                            <div class="row">
                                <a href="javascript:void(0)" id="btnSave" class="colourbutton button_blue"><span><span>
                                    Save</span></span></a> 
                                <a href="javascript:void(0)" id="btnCancel" class="colourbutton button_blue"><span><span>
                                    Cancel</span></span></a>
                                <div class="clr">
                                </div>
                            </div>
                        </fieldset>
                        </form>
    

    .val()

    The .val() method is primarily used to get the values of form elements such as input, select and textarea. To set a value we can use .val(value)

        //gets the value of textbox
        var myTextboxValue = $("#txtTitle").val();
    
       //set the value of textbox
       $("#txtTitle").val("This is my new value");
    
       //set value of elements with class mtext
       $("#frm .mtext").val("I am element with class mtext");
    

    .html() or .text()

    In an HTML document, .html() can be used to get the contents of any element. If the selector expression matches more than one element, only the first match will have its HTML content returned. Consider this code:

       var myDivContent = $("div.row").html();
    

    If there are multiple divs with class row as in our HTML, the first element is row is returned. If you set the value, it is set to all the selected elements. This is true to .val() also.

    .text() and .html() work similarly except that .text() retrieves only the text part without the HTML tags. For Example Consider the code below

        var myHTMLContent = $("div.formhearder").html();
    
        var myTextContent = $("div.formhearder").text();
    

    The first statement returns Jquery Selector enclosed within p tags but the the second statement returns only text part which is Jquery Selector.

    .attr() and .removeAttr()

    The .attr() can be used to get or set attribute values of HTML elements. Some of the common attribute values that can retrieved are ID, href, src, title, rel etc. .attr(attributename) can used to retrieve the attribute value and .attr(attributename,value) can be used to set attribute value as shown in example below

       //HTML
       <img id="myImage" src="image.gif" alt="An image" class="myClass" title="This is an image"/>   
       //javascript
       // retrieve attribute value
       var mySrc = $("#myImage").attr("src");
    
       //set the value 
       $("#myImage").attr("title","I am an Image");
    

    .attr() should not be used on plain objects, arrays, the window, or the document. To retrieve and change DOM properties, use the .prop() method.

    .removeAttr(attributename) can be used to remove attribute of an element as shown in the example below

        //removes the attributes title from the image
        $("#myImage").removeAttr("title");
    

    .addClass and .removeClass

    As the name suggests .addClass is used to add a class to an element. Please note that addClass adds a class to existing list of classes, it does not replace the classes

       //HTML
       <img id="myImage" src="image.gif" alt="An image" class="myClass" title="This is an image"/>  
      //add class
      $("#myImage").addClass("mysecondclass");
    
      // the output would be be
      <img id="myImage" src="image.gif" alt="An image" class="myClass mysecondclass" title="This is an image"/>  
    
      // and not 
      <img id="myImage" src="image.gif" alt="An image" class="mysecondclass" title="This is an image"/> 
    

    .removeClass([classname]) is used to remove class name of an element. If a class name is included as a parameter, then only that class will be removed from the set of matched elements. If no class names are specified in the parameter, all classes will be removed.

      //remove only mysecondclass class name 
      $("#myImage").removeClass("mysecondclass");
    
      //remove all the classes
      $("#myImage").removeClass();
    

    .toggleClass()

    This method takes one or more class names as its parameter. if an element in the matched set of elements already has the class, then it is removed; if an element does not have the class, then it is added. For example, we can apply .toggleClass() to above image

       $("#myImage").toggleClass("mysecondclass");
    

    It removes mysecondclass if it is present or adds toggleclass if it is missing.

    Be Sociable, Share!

    Written by

    Vanamali Juvvadi is a Web enthusiast and loves all things design and technology. Founded qnownow with a group of friends to share anything/everything they know/find on the internet.

    View all articles by

    Email : [email protected]

    Leave a Reply