jQuery: Get / set attribute values

This post describes how to get & set element’s attributes. Using jQuery you can get/set any attributes like id, class, style, name, title, etc. on any tag (<div>, <span>, <p>, etc.). This can be done using jQuery's .attr() and .prop() methods. If you are using jQuery version earlier than 1.6, then you have .attr() only.

The two methods are named accordingly to work with element's attributes and properties. The distinguish between them two was introduced in jQuery 1.6. For versions prior to 1.6 you don't need to worry about the difference and use .attr() in all cases. However, if you are working with newer versions of the library, you need to understand the difference between the two. You can read more about the difference between attributes and properties here and here. But before you dive into the details, let's see some examples.

Consider we have the following HTML tags on our page with corresponding attributes:

<div class="myContainer" id="wrapper">
  Some content 
  <a id="siteLink" title="Google" href="">link</a>
  <input type="checkbox" id="mycheckbox" checked="checked" />
</div>

In order to get container's id and the link's title attributes, we would use the following jQuery code:

// Get the ID of the selected div
var divID = $("div.myContainer").attr("id"); // "SiteLink"

// Get title attribute of a link
var linkTitle = $("#siteLink").attr("title"); // "Google"

// Get checkbox's "checked" state
$("#mycheckbox").prop("checked"); // returns boolean "true"
$("#mycheckbox").attr("checked"); // returns string "checked"

To set element’s attributes, you need to add it's value as the second parameter to the function.

// Add title to a link
$("a#siteLink").attr("title", "This is a link");

// Set table cell's collspan attribute
$("td.myDoubleCell").attr("colspan", 2);

// Mark checkbox as checked
$("#mycheckbox").prop("checked", true);

Additional notes

Here are some additional notes related to setting and getting attributes with jQuery that you should know:

  1. In most cases you use would want to use .prop() method. It is programmer friendly. It returns values of the right types which makes your code more readable and easy to understand, whereas .attr() always return string value. For example: .prop("checked") above returned boolean, style properties would return object with style properties that you can work on, etc.

  2. If jQuery selection returns more than one element, .attr()/.prop() functions would change only the first element’s attribute. If you need to change them all, you will have to do it in .each() loop.

    // Assume we have many links on our page
    $('a').prop('target', '_blank'); // Set target of the first link only
    
    // Setting the target of all links in the loop
    $('a').each(function(){
      $(this).prop('target', '_blank');
    });
  3. Finally, you are not limited to W3 Consortium defined set of HTML attributes. You can also set your own attributes with their own values.

    //This code adds myAttr attribute with the value of 10
    $("#container").attr("myAttr", "10");
    
    // Read the value
    $("#container").attr("myAttr");

jQuery Form Reset

This post shows you how to reset HTML form using jQuery. Also, in the notes section below, you will find a list of special cases and things to keep in mind while resetting form.

Please note that this post discusses 2 cases of resetting a form:

  1. Resetting form values to their default/initial values (similar to clicking on form "reset" button);
  2. Clearing form values (clearing form values, no matter what their default values were).

1. Reset form values

Probably, you already tried to use $("your-form").reset() method and got the following error:

TypeError: $(...).reset is not a function

That is because jQuery does not have .reset() method. However, DOM form elements have .reset() method. It resets form values to their initial values. In other words, if we had an input field with value="set on server" attribute set, and then, user typed in some other random text. On reset() that input fields value would be reset to "set on server" again and not to " ".

That out of the way, here is how you can reset a form using "pure" JavaScript.

// JavaScript only syntax
getElementById("your-form-id").reset();

// Using jQuery selectors
$('.my-form-class')[0].reset();

Here is a better way to reset your form with jQuery. Simply trigger a reset event on your form.

// jQuery syntax
$('.my-form-class').trigger("reset");

Notes on method 1

Things to remember:

  • Form values are reset to their initial/default values. They are not cleared/emptied.
  • Hidden values are not reset. If you have changed hidden input field values, you will have to reset them manually. You can do it by subscribing to reset event.

2. Clear form

The difference between clearing and resetting a form is that in clearing form values we clear all form fields. In other words, we will not reset them to their default values, but will replace their content with "" (empty space).

In other to do that, we will have to go through each field in the form and set its' value to "".

UPDATE: Replaced the code with the one from learningjquery.com. It creates a clearForm jQuery plugin.

$.fn.clearForm = function() {
  return this.each(function() {
    var type = this.type, tag = this.tagName.toLowerCase();
    if (tag == 'form')
      return $(':input',this).clearForm();
    if (type == 'text' || type == 'password' || tag == 'textarea')
      this.value = '';
    else if (type == 'checkbox' || type == 'radio')
      this.checked = false;
    else if (tag == 'select')
      this.selectedIndex = -1;
  });
};

Here is how to use clearForm jQuery plugin:

// Call it on your <form>
$('form').clearForm();

Notes on method 2

Put the plugin definition code into jquery.clearform.js file and include it your project.

jQuery: $.type()

This post covers all about jQuery’s .type() method. You will learn what it does, see its’ usage examples and understand the difference between jQuery’s .type() and JavaScripts’ typeof operator.

Without further ado, let’s find an answer to the following question.

What does $.type() do?

jQuery.type() method returns internal JavaScript class name of the passed argument.

jQuery.type(1)       // "number"
jQuery.type("foo")   // "string"
$.type(true)         // "boolean"
$.type(undefined)    // "undefined"
$.type(function(){}) // "function"
$.type(new Date())   // "date"
$.type(/test/)       // "regexp"
$.type(null)         // "null"

You might argue, why should I use jQuery .type() function when JavaScript already has native typeof operator that does just that. Well, you are in luck. In our previous post I explained why JavaScript’s typeof operator fails in what it’s supposed to do and excels in something else. Take the time and read the article.

When would you need it?

The method is very handy when writing a jQuery plugin or a function that can receive different type of arguments (e.g. $.css(Array or String)) or take optional parameters (e.g. $.click([eventData], function)).

In the case of $.click() method above:

/* You can either check:
  - eventData's type
  - fn === undefined
*/
click: function(eventData, fn){

    if($.type(fn) === "undefined"){
      fn = eventData;
      eventData = {default: "value"};
    }

}

Notes and Caveats

I would like to leave you with some notes on $.type() method:

  • as of jQuery 1.9 $.type(new Error()) will return "error"
  • if the argument type is not one of the list below, method will return "object":
    • Boolean
    • Number
    • String
    • Function
    • Array
    • Date
    • RegExp
    • Object
    • Error

One doesn't simply drop support for oldIE

This weeks humor post is about dropping IE 6, 7 and 8 support in the next jQuery 2.0 version.

One of the advantages of using jQuery is to get on with your app logic and not worry about the cross-browser scripting issues. I don't think anyone would trade their website's IE support for a digit in their jquery.js file. Would you?

One does not simply drop support for oldIE

JavaScript: typeof & when should you use it?

In this post, we will talk about JavaScript’s typeof operator. We will start with its’ purpose. Then discuss its’ flaws and finally see when should you use it.

typeof's usage doesn’t happen to match its’ initial purpose.

What is typeof?

The typeof operator is used to identify the type of an object. It always returns a String value, so you should always compare return value to a string.

// Examples
typeof 37;        // "number";
typeof true;      // "boolean"
typeof undefined; // "undefined"
typeof {};        // "object"

// Call with parentheses
typeof(37);        // "number";

As you can see above, there are 2 ways to call the method. typeof is an operand and not a function, that is why, the second method is actually not a function call. Operation in parentheses are evaluated and then passed to typeof.

So far, so good, we know its’ purpose. Now let’s see its’ flaws.

Flaws and caveats

I’ll just say it: typeof is one of the biggest flaws in JavaScript. It had only one job, to return the type of an object. But let’s see the table below (source):

Value               Class      Type
-------------------------------------
"foo"               String     string
new String("foo")   String     object
1.2                 Number     number
new Number(1.2)     Number     object
true                Boolean    boolean
new Boolean(true)   Boolean    object
new Date()          Date       object
new Error()         Error      object
[1,2,3]             Array      object
new Array(1, 2, 3)  Array      object
new Function("")    Function   function
/abc/g              RegExp     object   (function in Nitro/V8)
new RegExp("meow")  RegExp     object   (function in Nitro/V8)
{}                  Object     object
new Object()        Object     object
alert               Function   function (object in IE 6, 7, 8)
null                null       object   (in future ECMAScript versions)

"Type" column lists the typeof‘s return values and "Class" column shows the actual class of the operand.

As you can see, in most of the case you end up with object string instead of the actual class name. A workaround for getting the class of an object is to use Object.prototype.toString method. Here is how:

Object.prototype.toString.call("foo")      // [object string]
Object.prototype.toString.call(new String) // [object string]

As you can see, this is not the ideal return value. Here is a JavaScript function that would help make your code more readable (source):

function is(type, obj) {
    var clas = Object.prototype.toString.call(obj).slice(8, -1);
    return obj !== undefined && obj !== null && clas === type;
}

is('String', 'test');             // true
is('String', new String('test')); // true

If you want to check the type of an object, use Object.prototype.toString method instead of typeof operator. This would make your code behave as expected.

NOTE:
ECMAScript 5 changes the Object.prototype.toString method’s return values for null and undefined from object to null and undefined.

When should you use typeof?

typeof is good for checking if variables are undefined. If you make use of an undefined variable in your code, you will get a ReferenceError. Using typeof will not cause your code to throw an error.

if( typeof foo !== "undefined") {
    // defined
}else {
    // undefined
}

To conclude, unless you are checking whether a variable is defined or not, you should avoid using typeof.