Working with Selections

Contact Us or call 1-877-932-8228
Working with Selections

Working with Selections

Once you have a selection, you can call methods on the selection. Methods generally come in two different flavors: getters and setters. Getters return a property of the first selected element; setters set a property on all selected elements.

Getting and Setting Information About Elements

There are any number of ways you can change an existing element. Among the most common tasks you'll perform is changing the inner HTML or attribute of an element. jQuery offers simple, cross-browser methods for these sorts of manipulations. You can also get information about elements using many of the same methods in their getter incarnations.

jQuery "overloads" its methods, so the method used to set a value generally has the same name as the method used to get a value. When a method is used to set a value, it is called a setter. When a method is used to get (or read) a value, it is called a getter.

The getter methods return a single value from the first element in the collection, while the setters affect each element in the collection. (The lone exception is the text() method; as a getter, it returns the concatenation of the text content of all the elements in the collection.)

The $.fn.html Method Used as a Setter

$('h1').html('hello world');

The $.fn.html Method Used as a Getter

var content = $('h1').html();

Setters return a jQuery object, allowing you to continue to call jQuery methods on your selection; getters return whatever they were asked to get, meaning you cannot continue to call jQuery methods on the value returned by the getter.

Note: Changing things about elements is trivial, but remember that the change will affect all elements in the selection, so if you just want to change one element, be sure to specify that in your selection before calling a setter method.

  • $.fn.html - Get or set the html contents.
  • $.fn.text - Get or set the text contents; HTML will be stripped when getting, and escaped when setting (e.g., < will get turned into &lt;).
  • $.fn.attr - Get or set the value of the provided attribute.
  • $.fn.width - Get or set the width in pixels as an integer (for pixels) or a css string.
  • $.fn.height - Get or set the height.
  • $.fn.position - Get an object with position information for the first element in the selection, relative to its first positioned ancestor. This is a getter only.
  • $.fn.val - Get or set the value of form elements.

Changing the HTML of an Element

Code Sample:

jqy-concepts/Demos/changing-html.html
<html>
<head>
<script src="../../jqy-libs/jquery.js"></script> 
<script>
$(document).ready(function() {
	$('#myDiv p:first')
			.html('New <strong>first</strong> paragraph!');
});
</script>
</head>
<body>
<div id="myDiv">
	<h1>Changing HTML</h1>
	<p>Original first paragraph.</p>
	<p>Second paragraph.</p>
</div>
</body>
</html>

Try changing the html method call to text.

Next