jQuery 1.4 DOM Manipulation Methods for Style Properties and Class Attributes

Exclusive offer: get 50% off this eBook here
jQuery Reference Guide

jQuery Reference Guide — Save 50%

A Comprehensive Exploration of the Popular JavaScript Library

$23.99    $12.00
by Jonathan Chaffer Karl Swedberg | February 2010 | AJAX Open Source Web Development

All of the methods in this article by Karl Swedberg and Jonathan Chaffer, authors of jQuery 1.4 Reference Guide, manipulate the DOM in some manner. A few of them simply change one of the attributes of an element, while others set an element's style properties. All of these methods are referred to as setters, as they change the values of properties. A few of these methods such as .attr() also act as getters, retrieving information from DOM elements for later use.

General attributes

These methods get and set DOM attributes of elements.

.attr() (getter)

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

.attr(attributeName)

Parameters

  • attributeName: The name of the attribute to get

Return value

A string containing the attribute value.

Description

It's important to note that the .attr() method gets the attribute value for only the first element in the matched set. To get the value for each element individually, we need to rely on a looping construct such as jQuery's .each() method.

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

  • Convenience: It can be called directly on a jQuery object and chained to other jQuery methods.
  • 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.

.attr() (setter)

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

.attr(attributeName, value)
.attr(map)
.attr(attributeName, function)

Parameters (first version)

  • attributeName: The name of the attribute to set
  • value: A value to set for the attribute

Parameters (second version)

  • map: A map of attribute-value pairs to set

Parameters (third version)

  • attributeName: The name of the attribute to set
  • function: A function returning the value to set

Return value

The jQuery object, for chaining purposes.

Description

The .attr() method is a convenient and powerful way to set the value of attributes, especially when setting multiple attributes or using values returned by a function. Let's consider the following image:

<img id="greatphoto" src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="brush-seller.jpg"
alt="brush seller" />

Setting a simple attribute

We can change the alt attribute by simply passing the name of the attribute and its new value to the .attr() method.

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

We can 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, we can 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 quotation marks around attribute names are optional.

Computed attribute values

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

$('#greatphoto').attr('title', function() {
return this.alt + ' – photo by Kelly Clark'
});

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

.removeAttr()

Remove an attribute from each element in the set of matched elements.

.removeAttr(attributeName)
.removeAttr(function)

Parameters (first version)

  • attributeName: An attribute to remove

Parameters (second version)

  • function: A function returning the attribute to remove

Return value

The jQuery object, for chaining purposes.

Description

The .removeAttr() method uses the JavaScript removeAttribute() function, but it has the advantage of being able to be called directly on a jQuery object and it accounts for different attribute naming across browsers.

As of jQuery 1.4, the .removeAttr() function allows us to indicate the attribute to be removed by passing in a function.

jQuery Reference Guide A Comprehensive Exploration of the Popular JavaScript Library
Published: July 2007
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

Style properties

These methods get and set CSS-related properties of elements.

.css() (getter)

Get the value of a style property for the first element in the set of matched elements.

.css(propertyName)

Parameters

  • propertyName: A CSS property

Return value

A string containing the CSS property value.

Description

The .css() method is a convenient way to get a style property from the first matched element, especially in light of the different ways browsers access most of those properties (the getComputedStyle() method in standards-based browsers versus the currentStyle and runtimeStyle properties in Internet Explorer) and the different terms browsers use for certain properties. For example, Internet Explorer's DOM implementation refers to the float property as styleFloat, while W3C standards-compliant browsers refer to it as cssFloat. The .css() method accounts for such differences, producing the same result no matter which term we use. For example, an element that is floated left will return the left string for each of the following three lines:

  • $('div.left').css('float');
  • $('div.left').css('cssFloat');
  • $('div.left').css('styleFloat');

Also, jQuery can equally interpret the CSS and DOM formatting of multiple-word properties. For example, jQuery understands and returns the correct value for both .css('background-color') and .css('backgroundColor').

.css() (setter)

Set one or more CSS properties for the set of matched elements.

.css(propertyName, value)
.css(map)
.css(propertyName, function)

Parameters (first version)

  • propertyName: A CSS property name
  • value: A value to set for the property

Parameters (second version)

  • map: A map of property-value pairs to set

Parameters (third version)

  • propertyName: A CSS property name
  • function: A function returning the value to set

Return value

The jQuery object, for chaining purposes.

Description

As with the .attr() method, the .css() method makes setting properties of elements quick and easy. This method can take either a property name and value as separate parameters, or a single map of key-value pairs (JavaScript object notation). Also, jQuery can equally interpret the CSS and DOM formatting of multiple-word properties. For example, jQuery understands and returns the correct value for both .css({'background-color': '#ffe', 'border-left': '5px solid #ccc'}) and .css({backgroundColor: '#ffe', borderLeft: '5px solid #ccc'}). Notice that with the DOM notation, quotation marks around the property names are optional. However, with CSS notation they're required due to the hyphen in the name.

As with .attr(), .css() allows us to pass a function as the property value as follows:

$('div.example').css('width', function(index) {
return index * 50;
});

This example sets the widths of the matched elements to incrementally larger values.

.height() (getter)

Get the current computed height for the first element in the set of matched elements.

.height()

Parameters

None

Return value

The height of the element in pixels.

Description

The difference between .css('height') and .height() is that the latter returns a unitless pixel value (for example, 400), while the former returns a value with units intact (for example, 400px). The .height() method is recommended when an element's height needs to be used in a mathematical calculation.

 jQuery 1.4 Reference Guide

.height() (setter)

Set the CSS height of each element in the set of matched elements.

.height(value)

Parameters

  • value: An integer representing the number of pixels, or an integer with an optional unit of measure appended

Return value

The jQuery object, for chaining purposes.

Description

When calling .height(value), the value can be either a string (number and unit) or a number. If only a number is provided for the value, jQuery assumes a pixel unit. However, if a string is provided, any valid CSS measurement may be used for the height (such as 100px, 50%, or auto). Note that in modern browsers, the CSS height property does not include padding, border, or margin.

.innerHeight()

Get the current computed height for the first element in the set of matched elements, including padding but not border.

.innerHeight()

Parameters

None

Return value

The height of the element in pixels, including top and bottom padding.

Description

This method is not applicable to window and document objects; for these use .height() instead.

 jQuery 1.4 Reference Guide

.outerHeight()

Get the current computed height for the first element in the set of matched elements, including padding and border.

.outerHeight([includeMargin])

Parameters

  • includeMargin: A Boolean indicating whether to include the element's margin in the calculation

Return value

The height of the element, along with its top and bottom padding, border, and optionally margin, in pixels.

Description

If includeMargin is omitted or false, the padding and border are included in the calculation; if it's true, the margin is also included.

This method is not applicable to window and document objects, for these use .height() instead.

 jQuery 1.4 Reference Guide

.width() (getter)

Get the current computed width for the first element in the set of matched elements.

.width()

Parameters

None

Return value

The width of the element in pixels.

Description

The difference between .css(width) and .width() is that the latter returns a unitless pixel value (for example, 400), while the former returns a value with units intact (for example, 400px). The .width() method is recommended when an element's width needs to be used in a mathematical calculation.

 jQuery 1.4 Reference Guide

.width() (setter)

Set the CSS width of each element in the set of matched elements.

.width(value)

Parameters

  • value: An integer representing the number of pixels, or an integer along with an optional unit of measure appended

Return value

The jQuery object, for chaining purposes.

Description

When calling .width('value'), the value can be either a string (number and unit) or a number. If only a number is provided for the value, jQuery assumes a pixel unit. However, if a string is provided, any valid CSS measurement may be used for the width (such as 100px, 50%, or auto). Note that in modern browsers, the CSS width property does not include padding, border, or margin.

.innerWidth()

Get the current computed width for the first element in the set of matched elements, including padding but not border.

.innerWidth()

Parameters

None

Return value

The width of the element, including left and right padding, in pixels.

Description

This method is not applicable to window and document objects, for these use .width() instead.

 jQuery 1.4 Reference Guide

.outerWidth()

Get the current computed width for the first element in the set of matched elements, including padding and border.

.outerWidth([includeMargin])

Parameters

  • includeMargin: A Boolean indicating whether to include the element's margin in the calculation

Return value

The width of the element, along with left and right padding, border, and optionally margin, in pixels.

Description

If includeMargin is omitted or false, the padding and border are included in the calculation; if it's true, the margin is also included.

This method is not applicable to window and document objects; for these use .width() instead.

 jQuery 1.4 Reference Guide

.offset() (getter)

Get the current coordinates of the first element in the set of matched elements relative to the document.

.offset()

Parameters

None

Return value

An object containing the properties top and left.

Description

The .offset() method allows us to retrieve the current position of an element relative to the document. Contrast this with .position(), which retrieves the current position relative to the offset parent. When positioning a new element on top of an existing one for global manipulation (in particular, for implementing drag-and-drop), .offset() is more useful.

.offset() (setter)

Set the current coordinates of the first element in the set of matched elements relative to the document.

.offset(coordinates)

Parameters

  • coordinates: An object containing the top and left properties, which are integers indicating the new top and left coordinates for the element

Return value

The jQuery object, for chaining purposes.

Description

The .offset() setter method allows us to reposition an element. The element's position is specified relative to the document. If the element's position style property is currently static, it will be set to relative to allow for this repositioning.

.position()

Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.

.position()

Parameters

None

Return value

An object containing the properties top and left.

Description

The .position() method allows us to retrieve the current position of an element relative to the offset parent. Contrast this with .offset(), which retrieves the current position relative to the document. When positioning a new element near another one within the same DOM element, .position() is more useful.

.scrollTop() (getter)

Get the current vertical position of the scroll bar for the first element in the set of matched elements.

.scrollTop()

Parameters

None

Return value

The vertical scroll position in pixels.

Description

The vertical scroll position is the same as the number of pixels that are hidden from view above the scrollable area. If the scroll bar is at the very top, or if the element is not scrollable, this number will be 0.

.scrollTop() (setter)

Set the current vertical position of the scroll bar for each of the sets of matched elements.

.scrollTop(value)

Parameters

  • value: An integer indicating the new position to set the scroll bar to

Return value

The jQuery object, for chaining purposes.

.scrollLeft() (getter)

Get the current horizontal position of the scroll bar for the first element in the set of matched elements.

.scrollLeft()

Parameters

None

Return value

The horizontal scroll position in pixels.

Description

The horizontal scroll position is the same as the number of pixels that are hidden from view to the left of the scrollable area. If the scroll bar is at the very left, or if the element is not scrollable, this number will be 0.

.scrollLeft() (setter)

Set the current horizontal position of the scroll bar for each of the set of matched elements.

.scrollLeft(value)

Parameters

  • value: An integer indicating the new position to set the scroll bar to

Return value

The jQuery object, for chaining purposes.

jQuery Reference Guide A Comprehensive Exploration of the Popular JavaScript Library
Published: July 2007
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

Class attributes

These methods inspect and manipulate the CSS classes assigned to elements.

.hasClass()

Determine whether any of the matched elements are assigned the given class.

.hasClass(className)

Parameters

  • className: The class name to search for

Return value

A Boolean indicating whether the class is assigned to an element in the set.

Description

Elements may have more than one class assigned to them. In HTML, this is represented by separating the class names with a space:

<div id="mydiv" class="foo bar"></div>

The .hasClass() method will return true if the class is assigned to an element, and it will also return true if any other classes are assigned to it. For example, given the preceding HTML code, the following will return true:

  • $('#mydiv').hasClass('foo')
  • $('#mydiv').hasClass('bar')

.addClass()

Add one or more classes to each element in the set of matched elements.

.addClass(className)
.addClass(function)

Parameters (first version)

  • className: One or more class names to be added to the class attribute of each matched element

Parameters (second version)

  • function: A function returning one or more space-separated class names to be added

Return value

The jQuery object, for chaining purposes.

Description

It's important to note that this method does not replace a class. It simply adds the class, appending it to any which may already be assigned to the elements.

More than one class may be added at a time, separated by a space, to the set of matched elements.

$('p').addClass('myClass yourClass');

This method is often used with .removeClass() to switch elements' classes from one to another.

$('p').removeClass('myClass noClass').addClass('yourClass');

Here, the myClass and noClass classes are removed from all paragraphs; while yourClass is added.

As of jQuery 1.4, the .addClass() method allows us to set the class name by passing in a function.

$('ul li:last').addClass(function() {
return 'item-' + $(this).index();
});

Given an unordered list with five <li> elements, this example adds the item-4 class to the last <li>.

.removeClass()

Remove one or all classes from each element in the set of matched elements.

.removeClass([className])
.removeClass([function])

Parameters (first version)

  • className (optional): A class name to be removed from the class attribute of each matched element

Parameters (second version)

  • function (optional): A function returning one or more space-separated class names to be removed

Return value

The jQuery object, for chaining purposes.

Description

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.

More than one class may be removed at a time, separated by a space, from the set of matched elements.

$('p').removeClass('myClass yourClass')

This method is often used with .addClass() to switch elements' classes from one to another.

$('p').removeClass('myClass noClass').addClass('yourClass');

Here, the myClass and noClass classes are removed from all paragraphs; while yourClass is added.

To replace all existing classes with another class, we can use .attr('class', 'newClass') instead.

The .removeClass() method allows us to indicate the class to be removed by passing in a function.

$('li:last').removeClass(function() {
return $(this).prev().attr('class');
});

This example removes the class name of the penultimate <li> from the last <li>.

.toggleClass()

Add or remove a class from each element in the set of matched elements, depending on either its presence or the value of t he addOrRemove argumen t.

.toggleClass(className)
.toggleClass(className, addOrRemove)
.toggleClass(function[, addOrRemove])

Parameters (first version)

  • className: A class name to be toggled in the class attribute of each element in the matched set

Parameters (second version)

  • className: A class name to be toggled in the class attribute of each element in the matched set
  • addOrRemove: A Boolean indicating whether to add or remove the class

Parameters (third version)

  • function: A function that returns a class name to be toggled in the class attribute of each element in the matched set
  • addOrRemove (optional): A Boolean indicating whether to add or remove the class

Return value

The jQuery object, for chaining purposes.

Description

This method takes one or more class names as its parameter. In the first version, 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 a simple <div> as follows:

<div class="tumble">Some text.</div>

The first time we apply $('div.tumble').toggleClass('bounce'), we get the following:

<div class="tumble bounce">Some text.</div>

The second time we apply $('div.tumble').toggleClass('bounce'), the <div> class is returned to the single tumble value as follows:

<div class="tumble">Some text.</div>

Applying .toggleClass('bounce spin') to the same <div> alternates between <div class="tumble bounce spin"> and <div class="tumble">.

The second version of .toggleClass() uses the second parameter for determining whether the class should be added or removed. If this parameter's value is true, then the class is added; if false, the class is removed. In essence, the statement:

$('#foo').toggleClass(className, addOrRemove);

is equivalent to

if (addOrRemove) {
$('#foo').addClass(className);
}
else {
$('#foo').removeClass(className);
}

As of jQuery 1.4, the .toggleClass() method allows us to indicate the class name to be toggled by passing in a function.

$('div.foo').toggleClass(function() {
if ($(this).parent().is('.bar') {
return 'happy';
} else {
return 'sad';
}
});

This example will toggle the happy class for <div class="foo"> elements if their parent element has a class of bar; otherwise, it will toggle the sad class.

Summary

In this article we have covered the DOM manipulation methods for General attributes, Style Properties and Class Attributes. DOM insertion methods and DOM manipulation methods for Replacement, Copying and Removal are covered separately.


If you have read this article you may be interested to view :


About the Author :


Jonathan Chaffer

Jonathan Chaffer is a member of Rapid Development Group, a web development firm located in Grand Rapids, Michigan. His work there includes overseeing and implementing projects in a wide variety of technologies, with an emphasis in PHP, MySQL, and JavaScript. He also leads on-site training seminars on the jQuery framework for web developers.

In the open source community, he has been very active in the Drupal CMS project, which has adopted jQuery as its JavaScript framework of choice. He is the creator of the Content Construction Kit, a popular module for managing structured content on Drupal sites. He is also responsible for major overhauls of Drupal's menu system and developer API reference.

He lives in Grand Rapids with his wife, Jennifer.

Karl Swedberg

Karl Swedberg is a web developer at Fusionary Media in Grand Rapids, Michigan, where he spends much of his time making cool things happen with JavaScript. As a member of the jQuery team, he is responsible for maintaining the jQuery API site at api.jquery.com. He is also a member of jQuery's Board of Advisors and a presenter at workshops and conferences. When he isn't coding, he likes to hang out with his family, roast coffee in his garage, and exercise at the local CrossFit gym.

Books From Packt

jQuery UI 1.7: The User Interface Library for jQuery
jQuery UI 1.7: The User Interface Library for jQuery

jQuery 1.3 with PHP
jQuery 1.3 with PHP

Drupal 6 JavaScript and jQuery
Drupal 6 JavaScript and jQuery

AJAX and PHP: Building Modern Web Applications 2nd Edition
AJAX and PHP: Building Modern Web Applications 2nd Edition

Backbase 4 RIA Development
Backbase 4 RIA Development

CodeIgniter 1.7
CodeIgniter 1.7

TYPO3 4.3 Multimedia Cookbook
TYPO3 4.3 Multimedia Cookbook

Learning jQuery 1.3
Learning jQuery 1.3

Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software