jQuery’s .attr() Method

read 1 comment

In jQuery, the attribute or .attr() method is used to set the attributes values of selected elements. It works similarly to the .css() method, except with .attr(), you're not setting or changing the style rules, but the inline HTML attributes of a particular element. Common HTML attributes that can be altered are width and height, which are often applied to image (img) tags. Check out the example below to see how the .attr() method works.

JAVASCRIPT:
  1. <br />
  2. $(".main-img).click(function(){ $(this).attr("width","350px"); })<br />

The code above will change the width of the .main-img class to 350px when that class is clicked. The syntax for setting or changing the attribute of an HTML element is putting the attribute in quotations as the first parameter of the method, and then your desired value in quotations as the second parameter of the method, like this: .attr("attribute","value").

Continue Reading Below

If you want to use the .attr() method to set more than one value, the syntax changes a bit. The syntax actually becomes more similar to a CSS style rule, like this: .attr({attribute: value, attribute: value}). Here's what it looks like in action:

JAVASCRIPT:
  1. <br />
  2. $(".main-img).click(function(){ $(this).attr({width: 350px, height: 450px}); })<br />


comment feed

1 comment

  1. Tom

    It's working! Thanks, I've been looking for this.

Sorry, but comments for this entry are now closed.