jQuery API

.attr()

Contents:

.attr( attributeName ) Returns: String

Description: Get the value of an attribute for the first element in the set of matched elements.

  • version added: 1.0.attr( attributeName )

    attributeNameThe name of the attribute to get.

The .attr() method gets the attribute value for only the first element in the matched set. To get the value for each element individually, use a looping construct such as jQuery's .each() or .map() method.

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. In addition, .attr() should not be used on plain objects, arrays, the window, or the document. To retrieve and change DOM properties, use the .prop() method.

Using jQuery's .attr() method to get the value of an element's attribute has two main benefits:

  1. Convenience: It can be called directly on a jQuery object and chained to other jQuery methods.
  2. Cross-browser consistency: The values of some attributes are reported inconsistently across browsers, and even across versions of a single browser. The .attr() method reduces such inconsistencies.

Note: Attribute values are strings with the exception of a few attributes such as value and tabindex.

Example:

Find the title attribute of the first <em> in the page.

<!DOCTYPE html>
<html>
<head>
  <style>
  em { color:blue; font-weight;bold; }
  div { color:red; }
</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  
<p>
  Once there was a <em title="huge, gigantic">large</em> dinosaur...
</p>

  The title of the emphasis is:<div></div>

<script>
var title = $("em").attr("title");
  $("div").text(title);
</script>

</body>
</html>

Demo:

.attr( attributeName, value ) Returns: jQuery

Description: Set one or more attributes for the set of matched elements.

  • version added: 1.0.attr( attributeName, value )

    attributeNameThe name of the attribute to set.

    valueA value to set for the attribute.

  • version added: 1.0.attr( map )

    mapA map of attribute-value pairs to set.

  • version added: 1.1.attr( attributeName, function(index, attr) )

    attributeNameThe name of the attribute to set.

    function(index, attr)A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old attribute value as arguments.

The .attr() method is a convenient way to set the value of attributes—especially when setting multiple attributes or using values returned by a function. Consider the following image:

<img id="greatphoto" src="brush-seller.jpg" alt="brush seller" />

Setting a simple attribute

To change the alt attribute, simply pass the name of the attribute and its new value to the .attr() method:

$('#greatphoto').attr('alt', 'Beijing Brush Seller');

Add an attribute the same way:

$('#greatphoto')
.attr('title', 'Photo by Kelly Clark');

Setting several attributes at once

To change the alt attribute and add the title attribute at the same time, pass both sets of names and values into the method at once using a map (JavaScript object literal). Each key-value pair in the map adds or modifies an attribute:

$('#greatphoto').attr({
  alt: 'Beijing Brush Seller',
  title: 'photo by Kelly Clark'
});

When setting multiple attributes, the quotes around attribute names are optional.

WARNING: When setting the 'class' attribute, you must always use quotes!

Note: jQuery prohibits changing the type attribute on an <input> or <button> element and will throw an error in all browsers. This is because the type attribute cannot be changed in Internet Explorer.

Computed attribute values

By using a function to set attributes, you can compute the value based on other properties of the element. For example, to concatenate a new value with an existing value:

$('#greatphoto').attr('title', function(i, val) {
  return val + ' - photo by Kelly Clark'
});

This use of a function to compute attribute values can be particularly useful when modifying the attributes of multiple elements at once.

Note: If nothing is returned in the setter function (ie. function(index, attr){}), or if undefined is returned, the current value is not changed. This is useful for selectively setting values only when certain criteria are met.

Examples:

Example: Set some attributes for all <img>s in the page.

<!DOCTYPE html>
<html>
<head>
  <style>
  img { padding:10px; }
  div { color:red; font-size:24px; }
</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  
  <img />
  <img />
  <img />

  <div><B>Attribute of Ajax</B></div>

<script>
$("img").attr({ 
  src: "/images/hat.gif",
  title: "jQuery",
  alt: "jQuery Logo"
});
$("div").text($("img").attr("alt"));
</script>

</body>
</html>

Demo:

Example: Set the id for divs based on the position in the page.

<!DOCTYPE html>
<html>
<head>
  <style>
  div { color:blue; }
  span { color:red; }
  b { font-weight:bolder; }
        </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  
  <div>Zero-th <span></span></div>
  <div>First <span></span></div>
  <div>Second <span></span></div>

<script>
$("div").attr("id", function (arr) {
  return "div-id" + arr;
})
.each(function () {
  $("span", this).html("(ID = '<b>" + this.id + "</b>')");
});
</script>

</body>
</html>

Demo:

Example: Set the src attribute from title attribute on the image.

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  
<img title="hat.gif"/>

<script>
$("img").attr("src", function() { 
    return "/images/" + this.title; 
});
</script>

</body>
</html>

Demo:

Support and Contributions

Need help with .attr() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to .attr()? Report it to the jQuery core team.

Found a problem with this documentation? Report it to the jQuery API team.

* All fields are required
  • http://www.chrisdpratt.com Chris Pratt

    The format you suggest is the same format for returning the current value of an attribute. The only way jQuery could do what you ask is to have some static list of boolean attributes that it would check against before returning a value to make sure it shouldn’t set the attribute instead. Not only does this add needless overhead, what if you actually want to know whether those boolean attributes are set? What should jQuery do then?

    The best solution: stop being lazy.

  • silver

    HTML5 does not actually have boolean attributes, it allows you to say but it is defined to be precisely equal to . This can apply to any attribute, not just ones currently defined as boolean. is just like saying that the default value is blank.
    It’s unclear if browsers will support this as written or bend the rules for “certain boolean attributes.” But that is moot here.

    Your question used the syntax for “getting an attribute value” but you seemed to imply you wanted it to set the value. That is clearly wrong.

    The syntax for setting an attribute in jquery might look like:
    $(:input).attr(‘disabled’, ”); // sets disabled=” as html5 theoretically specifies
    $(:input).attr(‘disabled’, ‘disabled’); // sets disabled=’disabled’ as required in xhtml
    $(:input).attr(‘disabled’, ‘true’); // sets disabled=’true’, which experimentation shows is currently what jquery returns for ” in html4

    Against html4,
    $(“#foo”).attr(‘disabled’) returns ‘true’
    $(“#foo”).attr(‘disabled’) returns ‘false’


    As for Chris’ mention of “a static list of boolean attributes” – it seems to already have such a list, which is what it consults when it fulfills “Cross-browser consistency: Some attributes have inconsistent naming from browser to browser. Furthermore, the values of some attributes are reported inconsistently across browsers, and even across versions of a single browser. The .attr() method reduces such inconsistencies.”

  • http://richa.avasthi.name/blogs/tepumpkin Richa Avasthi

    Can we add documentation for the get function specifying the return value if the attribute is not present? (I'm pretty sure the old documentation site said .attr() returns undefined if attributeName is not an attribute of the element, but it should be written here.)

  • http://twitter.com/m2ew m2ew

    Beginner tip:
    Be weary of using .attr() to attach set classes in safari. Use .removeClass or .addClass to assign your class as it won’t compile your function.

  • http://paraondeestamosindo.blogspot.com/ Couto

    It also didn’t work in Firefox 3.5.7 in Linux.

  • Chris

    There doesn’t appear to be a way of distinguish an empty attribute vs a missing one. Example:

    $(“#mydiv”).attr(“data-foo”) -> undefined
    $(“#mydiv”).attr(“data-bar”) -> undefined

    The first case should really return a zero-length string.

  • http://jasonlau.biz Jason Lau

    $(this).attr(‘type’,'submit’); Throws an exception.

  • http://twitter.com/jethrolarson Jethro Larson

    Since IE doesn't allow dynamic changing the type of an input, the jquery team chose to throw an exception when you try.

  • http://tgwebsolutions.com/ Tim Gallagher

    Note that under Chrome (and presumably any browser that implements HTML5) the attribute ‘required’ is a boolean value. If required is present at all true is returned, if it’s not then false is returned.

    I was using required=”no” for validation on form fields and the true/false being backwards was really throwing me off.

  • michaelriddle

    jQuery as of 1.4.2 does not support an easy way to get a list of all attributes of an element so I wrote a plugin for it. It is freely available on Google Code and is licensed under the MIT license.
    http://code.google.com/p/jquery-list-attributes/

  • stephenrs

    My understanding is that IE doesn't allow dynamic changing of the type of an input only AFTER it's been added to the DOM. So, code that looks like this:

    var oldPwd = $('#password-input');
    var newPwd = oldPwd.clone();
    newPwd.attr('type', 'text');
    newPwd.insertBefore(oldPwd);
    oldPwd.remove();

    Should be a legitimate workaround for the IE problem…but since jquery throws an exception, there unfortunately seems to be no way to workaround IE's useless attempt at security using jquery alone…

  • Bodyscanner

    I have an img with style=”width:100%; height:100%” in a container. Also it has the width/height attribute values set. Calling $ele.attr(‘width’) does not return the value of the width attribute but the size onscreen – how to get the width attribute value?

  • eithe

    Bear in mind that when adding event attributes (mousedown, load) you will need to retain proper case of attribute name – for example:

    $(object).attr('onmousedown','functioncall()') – will work in Firefox but it won't work in Chrome, as the proper name of this event is onMousedown. In Chrome's case the attribute won't be set.

    sorry if it's a repeat – couldn't find any results for this bug.

  • http://www.learningjquery.com/ Karl Swedberg

    You'd probably need to use .getAttribute() on the DOM node: $ele[0].getAttribute('width');

  • Timo Frenay

    “[...] the proper name of this event is onMousedown.”

    This isn't actually true, nor is it in Chrome (which you can easily check using its built-in javascript console). Of course you should be using $(object).mousedown(functioncall) anyway.

  • jawsper

    Seems like this doesn't work either:

    $('<button>').attr('type','button').text('Button text');

    Had to do $('<input>').attr({'type':'button','value':'Button text'});

  • http://www.learningjquery.com/ Karl Swedberg

    It makes sense that .text() doesn't work, since you aren't setting the text content. You could have done .val('Button text'), but the way you did it is fine, too.

  • http://www.elypsia.fr Anthony PLASSAIS

    Hi everyone !
    I were unable to change the “action” attribute of a “<form>”.

    Assuming the html source :
    <form action=”myaction.html” method=”post”> … </form>

    The getter method jQuery(“#formId”).attr('action') returns correctly the string “myaction.html”.
    But the setter method jQuery(“#formId”).attr('action', 'mynewaction.html') doesn't work.

    In order to work, we seem to have to call the setter method with the attribute in uppercase like : jQuery(“#formId”).attr('ACTION', 'mynewaction.html').

    It was the only way for me …

  • http://twitter.com/longears Devin Baldwin

    checking the attr() on a custom tag does not behave like checking for the disabled attribute. If I create the custom tag “required” in:and get the attribute through jQuery:$(‘input’).attr(‘required’);Chrome will return true if it is set and false if it is not set.The description of this tag states “If we try to get the value of an attribute that has not been set, the .attr() method returns undefined.” which is false.until this is fixed, here is an easy workaround:if($(‘input’).attr(‘required’) === undefined || $(‘input’).attr(‘required’) === false) …

  • JC

    not able to apply the id value dynamically using attr() method
    $(“span”).each(function(index) {
    $(this).attr(“id”,index);
    });

    not working as expected .. the id is not applied at all for the spans, any ideas guys ?

  • Charles B

    How do you set the a href attribute?

  • JC

    $(“a”).attr(“href”,”http://www.google.com”);

  • Rajput Joni

    Hi ,
    I implement action attribute like $(“#formId”).attr('action' ,'action.html'); and using ACTION also. Both are doing correctly work.So I am not agree with your statement.

  • Charles B

    Thanks. That worked but I am using a for loop and now all of the urls in the array are the same no matter what. It worked for a second and then it stopped looping through the urls and only one would show up all the time.

    var featurePics = new Array(
    “img/feature-trevi.jpg”,
    “img/feature-arch.jpg”,
    “img/feature-santamaria.jpg”,
    “img/feature-trajan.jpg”,
    “img/feature-vittoriano.jpg”,
    “img/feature-locks.jpg”
    );
    var featureText = new Array(
    “Fontana di Trevi (Trevi Fountain), 1762″,
    “Arco di Constantino (Arch of Constantine), 315 AD”,
    “Santa Maria Maggiore”,
    “Colonna Traiana (Trajan’s Column), 113 AD”,
    “Il Vittoriano, 1911″,
    “Locks near Trevi Fountain”
    );
    var featureUrl = new Array(
    “http://www.twitter.com”,
    “http://www.facebook.com”,
    “http://www.cnn.com”,
    “http://www.hotmail.com”,
    “http://www.yahoo.com”,
    “http://www.jquery.com”
    );
    // loop through them all
    for(var x=0; x<featurePics.length; x++){
    // create a placeholder anchor and empty image for the cycle script to be able to act on
    var newImage = jQuery('<img>');
    // add the needed data for later use
    newImage.data(“pic”,featurePics[x])
    .data(“text”,featureText[x])
    .data(url”,featureUrl[x])
    // bind an event that we can trigger later
    .bind(“loadImage”,function(){
    var self = this;
    // console.debug(“loading image “+$(this).data(“pic”));
    // find the empty img and bind a load event to that so that when the image is done loading we will move on to the next image and load it
    jQuery(this).find(“img”).hide().bind(“load”,function(){
    // console.debug(“loaded”,this);
    // trigger the load of the next image
    jQuery(this).fadeIn(“slow”);
    jQuery(self).next().trigger(“loadImage”);
    })
    // now that we have the trigger, lets add the src and alt for the image. the above load will fire when this is done
    .attr(“src”,$(self).data(“pic”))
    .attr(“alt”,$(self).data(“text”))
    $(“a”).attr(“href”,$(self).data(“url”));
    })

    jQuery(“#carousel-photos”).append(newImage);
    }

  • Charles B

    This is the code for the newimage var:
    var newImage = jQuery('<img>');

    Just take out the period. It made a hyperlink that's why I posted it again.

    Thanks.

  • Charles B

    This is the code for the newimage var:
    var newImage = jQuery('<img>');

    Just take out the period. It made a hyperlink that's why I posted it again.

    Thanks.

  • Charles B
    var newImage = jQuery('<img>');
  • JC

    Put all the url string in an array .. give the corresponding array index as the value for the href using attr method

    this is the way of setting the href attr

    $(“a”).attr(“href”,array[index]);

  • sanath reddy

    let u try like this $(this).attr('id');

  • Paul Moment

    FYI, in case anyone runs into it: Doing a test for the 'maxlength' attr on a form field like $(“#field”).attr(“maxlength”) doesn't actually return “undefined” in IE or Safari (seemed to be fine in FF). Instead, what I got was a really long integer that looked like a browser-standard maxlength. The integer was different in IE and Safari, but pretty long. So, I had to do some class checking instead to do a workaround. Checking something like $(“#field”).attr(“cheese”) actually returned an “undefined” as expected.

  • Bruno

    $(“a”).attr(“onclick”) doesn't return the string the attribute contains. How could I fix it?

  • Kyle Dickerson

    I'm seeing the same issue ('ACTION' must be capitalized). I'm using jQuery 1.4.1 and Firefox 3.6.6

  • http://www.learningjquery.com/ Karl Swedberg

    it's probably not working because IDs aren't allowed to begin with a number, let alone be a number in their entirety. See if this works:

    $('span').attr('id', function(index) {
    return 'span-' + index;
    });

  • http://twitter.com/edtimmons Ed Timmons

    Me too using jquery 1.4.2, lowercase + uppercase work in safari 5.0, only uppercase works in Firefox 3.6.7

  • http://twitter.com/shackpank Ollie Buck

    Hi
    'action' all lower case works normally – it may be that your form contained an input named “action”?
    <form action=”one”>
    <input name=”action” value=”two” />
    </form>

    $('form').attr('action') will return 'one' as expected, but $('form').attr('action', 'test') doesn't modify it. If you use 'Action' or 'ACTION' it will change the attribute on the form.

    Only applies to forms, & same issue exists with using hidden inputs named 'method', 'target' etc. Changing the case as you describe works as a workaround

  • http://twitter.com/shackpank Ollie Buck

    Hi
    'action' all lower case works normally – it may be that your form contained an input named “action”?
    <form action=”one”>
    <input name=”action” value=”two” />
    </form>

    $('form').attr('action') will return 'one' as expected, but $('form').attr('action', 'test') doesn't modify it. If you use 'Action' or 'ACTION' it will change the attribute on the form.

    Only applies to forms, & same issue exists with using hidden inputs named 'method', 'target' etc. Changing the case as you describe works as a workaround

  • http://twitter.com/shackpank Ollie Buck

    Hi
    'action' all lower case works normally – it may be that your form contained an input named “action”?
    <form action=”one”>
    <input name=”action” value=”two” />
    </form>

    $('form').attr('action') will return 'one' as expected, but $('form').attr('action', 'test') doesn't modify it. If you use 'Action' or 'ACTION' it will change the attribute on the form.

    Only applies to forms, & same issue exists with using hidden inputs named 'method', 'target' etc. Changing the case as you describe works as a workaround

  • http://twitter.com/westwestphp westwest

    You should use $ele.css('width') because that's a css property, not an attribute

  • http://www.learningjquery.com/ Karl Swedberg
  • http://mfabrik.com/ Mikko Ohtamaa

    You cannot use attr() with <button value=”"> with IE6 or IE7

    http://stackoverflow.com/questions/487056/retri…

  • Eric Thibault

    when I change the href of a text link, Internet Explorer also changes the text attribute! in FireFox all is good! When I change the href of an image, both browsers performs ok.
    Any hint?

  • kevin

    Does this work with the new html5 data-* attributes? Or do I need to do something like this http://binarykitten.me.uk/dev/jq-plugins/288-ht…

  • kevin

    don’t you still need the .each?

  • http://www.learningjquery.com/ Karl Swedberg

    No, you don't need the .each if you're using a function for the second argument.

  • jade.zhong

    yes, same problem, weird…

  • Harold Dennison

    same problem here, but this time trying to change “type”. “Type” works fine

  • Tomasteicher

    .attr() method ca be used to set unsupported attributes in xhtml. For example this could be done:
    $('#mytext').attr('abc', 'a');
    alert($('#mytext').attr('abc'));

    I like this possibility. But I am not sure whether it is a benevolence or intent that it works like that.

  • http://twitter.com/kostia_b Konstantin

    It seems to me, that if we try to get the value of an attribute that has not been set, method returns false, but not 'undefined'.

  • Kayla Rose

    I have the same “type” problem in IE8.

    $(‘#some_li’).attr(“type”) returns “” (empty string)
    $(‘#some_li’).attr(“Type”) and $(‘#some_li’).attr(“TYPE”) both return the correct value

  • k00ni

    If you getting errors like

    Uncaught TypeError: Object XYZ has no method 'attr' (in Chrome)

    than you can take the following way:

    $( $ ( … $ ( 'your_element' ) … ).attr ( 'foo') ).attr ( 'bar' );

    for accessing your target element.

  • Frederik

    It is indeed a nice possibility, but it does break the validity of an XHTML document. A document would still run as valid XHTML, as the manipulation of the DOM appears after load.

  • http://pric.co.uk N Hayath

    thanks that helped

  • Rihards

    I'm having the same problem.
    Also after setting: $(“a”).attr(“onclick”, “doSomething();”)
    Once it fires first time, the second time button ignores that it has this attribute onclick.

  • http://twitter.com/amielucha amielucha

    Yes and that's a great feature.

    I am using it to attach and retrieve real-world dimensions of images.
    Example:

    <img data-height=”30cm” data-width=”20cm” src=”foo.jpeg”>

    alert( $('img').attr('data-width') );

  • inspire22

    You need to set the binding.. When the HTML parser reads the onclick attribute, it sets a binding for that element, rather than an attribute. Its confusing, yeah.

    $('a').click( function() { what to do here })

    (wrapped in $(document).ready of course)

    No, as far as I know, there's no way to get the 'source code' of what was in the onclick attribute before.

  • CodenameNinja

    Hi. I am trying to append text to the URL in the href of an anchor tag using the title attribute
    eg.

    a title=”test” href=”default.aspx” —- This is what it looks like now
    a title=”test” href=”default.aspx?extratext” —- This is what I want it to look like

    This is the jquery I got there now:
    $('a[title=Broadband]').append('?campaign=notw');

  • Cosmin

    Hello ; i have a page where i generate new elements with the “append” function . The “attr” is called each second to modify the values from some elements . Let say $(“#ID1″).attr(“value”) = “a new value” and so on. After the new element is generated, the values from the previous elements are still changing but the value from the new generated element stays still . How can i solve this problem?

  • http://www.learningjquery.com/ Karl Swedberg

    No, not when you you're using a function for the second argument. jQuery uses “implicit iteration” in that case.

  • FX

    when i use “attr” in vision 1.4.2 on a click function,the code : $(event).attr(“altKey”),the result is right,now in vision 1.4.3 the code result is “undifined” why???

  • http://www.learningjquery.com/ Karl Swedberg

    Interesting. Not sure if this is a bug or not. The standard way to access properties of any object (including, in this case, the event object) is directly using either “dot notation” or “array notation.” If neither event.altKey nor event['altKey'] works, please file a bug at http://bugs.jquery.com/. Thanks!

  • http://twitter.com/therandshow Rand McRanderson

    $(“element”).attr(“bad-attr”)==false, but not $(“element”).attr(“bad-attr”)===false – undefined (although I've found IE inconsistent about this) generally casts as a boolean to false

  • http://twitter.com/chadhikes Chad Killingsworth

    The raw XML lists the value parameter of attr to be of type “Object”. Shouldn't it be more like string/number? Or are there specific cases when an actual object would be assigned to an attribute?

  • http://www.learningjquery.com/ Karl Swedberg

    Sorry, that was an error. Fixed now. Thanks!

  • Mtirisu

    Can I enumerate attributes?

  • David

    I have tried this in the document ready section and nothing happens. Previously we had, $(location).attr('href',url); Which worked.
    In version 1.4.4 this no longer works, nor does your method.
    Am I missing out a step?

  • Mathieu

    Same problem for me in version 1.4.3 !

  • http://www.learningjquery.com/ Karl Swedberg

    Interesting. I’ve never tried that. I would recommend you just do location.href = url instead.

  • Macielo

    Using dijit.byID('elementID').attr('value') to get the current value of an element doesn't work twice after doing a dijit.byID('elementID').attr('value',newValue)

    I have a function that calls twice that code and it keeps the first value.

  • quiff

    how would i change style=”left:0%” to style=”right:0%” ?

  • Steve

    $div = $('#div'); $div.attr('style', $div.attr('style').replace('right', 'left'));

  • Steve

    $div = $('#div'); $div.attr('style', $div.attr('style').replace('right', 'left'));

  • Steve

    $div = $('#div'); $div.attr('style', $div.attr('style').replace('right', 'left'));

  • Steve

    actually swap the right and left around to get your desired effect

  • Steve

    actually swap the right and left around to get your desired effect

  • Steve

    actually swap the right and left around to get your desired effect

  • quiff

    It working great, thanks

  • kennethjayden

    .attr doesn't seem to work well with forms on IE.

    $('#some_form').attr('action','some_script.php');
    alert($('#some_form').attr('action'));

    the output will be undefined.

    =/

  • Bobo_mayday2007

    OK I agree with u thanks !

  • http://pulse.yahoo.com/_7MOKQBK44A5AY4IZP4HNHY4V4M Bob

    is $image.attr('src') the corrrect way to get src attribute?

  • Sean

    It would be nice if omitting any parameters to attr() would return a map of all the attributes. In this way you could essentially copy attributes from one element to another with a subsequent call to attr() passing the map in the second call, retrieved from the first call

  • Srinivasan Sriit

    how to get the attr value using jquery

  • Ian

    $(“#element”).attr(“attr”, value);
    :3

  • Ian

    $(“#element”).attr(“attr”, value);
    :3

  • Ricky Cobb III

    Pretty nice feature of jquery. So I needed to cancel out an animation if clicking on a footer link (who's parent's parent's attribute id was #nav2) and came up with this:

    if ($(this).parent().parent().attr('id') == “nav2″ ) { animDelay = 0; } //had animDelay set in my code to turn on or off animation
    //the neat part is the chained parents and making it so easy to test for stuff like this :)

  • Olivier Combe

    I found a nasty bug on IE 7 :

    img.attr(“oldOnClick”,img.attr(“onClick”));

    this works fine on all browsers except IE7 which will execute the onClick function when you do that… I solved it by doing :

    img.attr(“oldOnClick”,'”'+img.attr(“onClick”)+'”');

  • Olivier Combe

    As a matter of fact this caused me another bug on firefox so i found a proper solution, just use :
    img.attr(“oldOnClick”,”"+img.attr(“onClick”));

    it will force the attr value to be cast as a string

  • Heinz

    In <area>-tags the shape-attribute is not recognised.

    Deleting areas with no shapes doesn't work:
    focusable = focusable.map(function(){return($(this).attr('shape') === undefined && $(this).is('area')) ? null : this;});

    Deleting areas with no href works:
    focusable = focusable.map(function(){return($(this).attr('href') === undefined && $(this).is('area')) ? null : this;});

  • Michele

    Hi, I have an input element named password and i should set the type to 'password' when focus the input. I tried the following code, but it doesn't work.

    $(“#password”).focus(function () {
    $(“#password”).attr('type', 'password');
    });

    Could someone help me? thanks.

  • Seb

    Try this:

    $('#password').focus(function() {

    this.type = 'password';

    });

  • Tomas Turbando Soares

    $('.myClass').attr('readonly', 'readonly'); //Works perfectly
    But…
    $('.myClass').attr('readonly', ''); //It keeps the “readonly” property but without a value, how can i remove completely the property?

  • Tomas Turbando Soares

    $('.myClass').attr('readonly', 'readonly'); //Works perfectly
    But…
    $('.myClass').attr('readonly', ''); //It keeps the “readonly” property but without a value, how can i remove completely the property?

  • Tomas Turbando Soares

    $('.myClass').attr('readonly', 'readonly'); //Works perfectly
    But…
    $('.myClass').attr('readonly', ''); //It keeps the “readonly” property but without a value, how can i remove completely the property?

  • Tomas Turbando Soares

    I don't know if this is the right way, but i just put “undefined” as the value

    $('.myClass').attr('readonly', undefined);
    Apparently it works

  • Tomas Turbando Soares

    I don't know if this is the right way, but i just put “undefined” as the value

    $('.myClass').attr('readonly', undefined);
    Apparently it works

  • Tomas Turbando Soares

    I don't know if this is the right way, but i just put “undefined” as the value

    $('.myClass').attr('readonly', undefined);
    Apparently it works

  • Tomas Turbando Soares

    Sorry. my mistake , there is .removeAttr()

    Hope it helps anyone with same problem. I think it should be explained on this section.

  • Tomas Turbando Soares

    Sorry. my mistake , there is .removeAttr()

    Hope it helps anyone with same problem. I think it should be explained on this section.

  • Tomas Turbando Soares

    Sorry. my mistake , there is .removeAttr()

    Hope it helps anyone with same problem. I think it should be explained on this section.