- jQuery 1.4 Reference Guide
- Jonathan Chaffer Karl Swedberg Karl Swedberg
- 1545字
- 2025-02-18 07:15:24
Miscellaneous traversal methods
These methods provide other mechanisms for manipulating the set of matched DOM elements in a jQuery object.
.add()
Note
Add elements to the set of matched elements.
.add(selector[, context]) .add(elements) .add(html)
Parameters (first version)
selector
: A string containing a selector expression to match additional elements againstcontext
(optional): The portion of the DOM tree within which to search
Parameters (second version)
elements
: One or more elements to add to the set of matched elements
Parameters (third version)
html
: An HTML fragment to add to the set of matched elements
Return value
The new jQuery object.
Description
Given a jQuery object that represents a set of DOM elements, the .add()
method constructs a new jQuery object from the union of those elements and the ones passed into the method. The argument to .add()
can be pretty much anything that $()
accepts, including a jQuery selector expression, references to DOM elements, or an HTML snippet.
Consider a page with a simple list along with a couple paragraphs as follows:
<ul> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> </ul> <p>a paragraph</p> <div> <p>paragraph within a div</p> </div>
We can select the list items and then the paragraphs by using either a selector or a reference to the DOM element itself as the .add()
method's argument.
$('li').add('p').css('background-color', 'red');
or
$('li').add(document.getElementsByTagName('p')[0]) .css('background-color', 'red');
The result of this call is a red background behind all three list items and two paragraphs.
We can specify a context within which to search for the elements that we wish to add:
$('li').add('p', 'div').css('background-color', 'red');
Now the result is a red background behind all three list items, but only the second paragraph.
Using an HTML snippet as the .add()
method's argument (as in the third version), we can create additional elements on the fly and add those elements to the matched set of elements. Let's say, for example, that we want to alter the background of the list items along with a newly created paragraph.
$('li').add('<p id="new">new paragraph</p>') .css('background-color', 'red');
Although the new paragraph has been created and its background color changed, it still does not appear on the page. To place it on the page, we could add one of the insertion methods to the chain.
Note
See Chapter 4, DOM Manipulation Methods, for more information about the insertion methods.
.is()
Note
Check the current matched set of elements against a selector and return true
if at least one of these elements matches the selector.
.is(selector)
Parameters
selector
: A string containing a selector expression to match elements against
Return value
A Boolean indicating whether an element matches the selector.
Description
Unlike the rest of the methods in this chapter, .is()
does not create a new jQuery object. Instead, it allows us to test the contents of a jQuery object without modification. This is often useful inside callbacks, such as event handlers.
Suppose we have a list, with two of its items containing a child element as follows:
<ul> <li>list <strong>item 1</strong></li> <li><span>list item 2</span></li> <li>list item 3</li> </ul>
We can attach a click handler to the <ul>
element, and then limit the code to be triggered only when a list item itself, not one of its children, is clicked.
$('ul').click(function(event) { if ($(event.target).is('li') ) { $(event.target).css('background-color', 'red'); } });
Now, when the user clicks on the word list in item 1, or anywhere on item 3, the clicked list item will be given a red background. However, when the user clicks on item 1 in the first item or anywhere in the second item, nothing will happen because in those cases the target of the event would be <strong>
or <span>
, respectively.
.end()
Note
End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.
.end()
Parameters
None
Return value
The previous jQuery object.
Description
Most of the methods in this chapter operate on a jQuery object and produce a new one that matches a different set of DOM elements. When this happens, it is as if the new set of elements is pushed onto a stack that is maintained inside the object. Each successive filtering method pushes a new element set onto the stack. If we need an older element set, we can use .end()
to pop the sets back off of the stack.
Suppose we have a couple short lists on a page as follows:
<ul class="first"> <li class="foo">list item 1</li> <li>list item 2</li> <li class="bar">list item 3</li> </ul> <ul class="second"> <li class="foo">list item 1</li> <li>list item 2</li> <li class="bar"></ul>
The .end()
method is useful primarily when exploiting jQuery's chaining properties. When not using chaining, we can usually just call up a previous object by a variable name so that we don't need to manipulate the stack. With .end()
, though, we can string all of the method calls together.
$('ul.first').find('.foo').css('background-color', 'red') .end().find('.bar').css('background-color', 'green');
This chain searches for items with the foo
class within the first list only and turns their backgrounds red. Then .end()
returns the object to its state before the call to .find()
. So the second .find()
looks for '.bar'
inside <ul class="first">
, not just inside that list's <li class="foo">
, and turns the matching elements' backgrounds green. The net result is that items 1
and 3
of the first list have a colored background, while none of the items from the second list do.
A long jQuery chain can be visualized as a structured code block with filtering methods providing the openings of nested blocks and .end()
methods closing them:
$('ul.first').find('.foo') .css('background-color', 'red') .end().find('.bar') .css('background-color', 'green') .end();
The last .end()
is unnecessary, as we are discarding the jQuery object immediately thereafter. However, when the code is written in this form, the .end()
provides visual symmetry and closure, making the program more readable at least in the eyes of some developers.
.andSelf()
Note
Add the previous set of elements on the stack to the current set.
.andSelf()
Parameters
None
Return value
The new jQuery object.
Description
As previously described in the Description for .end(), jQuery objects maintain an internal stack that keeps track of changes to the matched set of elements. When one of the DOM traversal methods is called, the new set of elements is pushed onto the stack. If the previous set of elements is desired as well, .andSelf()
can help.
Consider a page with a simple list as follows:
<ul> <li>list item 1</li> <li>list item 2</li> <li class="third-item">list item 3</li> <li>list item 4</li> <li>list item 5</li> </ul>
If we begin at the third item, we can find the elements that come after it.
$('li.third-item').nextAll().andSelf() .css('background-color', 'red');
The result of this call is a red background behind items 3
, 4
and 5
. First, the initial selector locates item 3
, initializing the stack with the set containing just this item. The call to .nextAll()
then pushes the set of items 4
and 5
onto the stack. Finally, the .andSelf()
invocation merges these two sets together, creating a jQuery object that points to all three items.
.map()
Note
Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.
.map(callback)
Parameters
callback
: A function object that will be invoked for each element in the current set
Return value
The new jQuery object.
Description
The .map()
method is particularly useful for getting or setting the value of a collection of elements. Consider a form with a set of checkboxes as follows:
<form method="post" action=""> <fieldset> <div> <label for="two">2</label> <input type="checkbox" value="2" id="two" name="number[]"> </div> <div> <label for="four">4</label> <input type="checkbox" value="4" id="four" name="number[]"> </div> <div> <label for="six">6</label> <input type="checkbox" value="6" id="six" name="number[]"> </div> <div> <label for="eight">8</label> <input type="checkbox" value="8" id="eight" name="number[]"> </div> </fieldset> </form>
We can select all of the checkboxes by setting their checked
property to true
.
$(':checkbox').map(function() { return this.checked = true; });
We can get the sum of the values of the checked inputs as follows:
var sum = 0; $(':checked').map(function() { return sum += (this.value * 1); });
We can get a comma-separated list of checkbox IDs.
$(':checkbox').map(function() { return this.id; }).get().join(',');
The result of this call is the two,four,six,eight
string.
.contents()
Note
Get the children of each element in the set of matched elements, including text nodes.
.contents()
Parameters
None
Return value
The new jQuery object.
Description
Given a jQuery object that represents a set of DOM elements, the .contents()
method allows us to search through the immediate children of these elements in the DOM tree and construct a new jQuery object from the matching elements. The .contents()
and .children()
methods are similar, except that the former includes text nodes as well as HTML elements in the resulting jQuery object.
Consider a simple <div>
with a number of text nodes, each of which is separated by two line break elements (<br />
) as follows:
<div class="container"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. <br /><br /> Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.<br /><br /> Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </div>
We can employ the .contents()
method to help convert this block of text into three well-formed paragraphs.
$('.container').contents().filter(function() { return this.nodeType == 3; }) .wrap('<p></p>') .end() .filter('br') .remove();
This code first retrieves the contents of <div class="container">
and then filters it for text nodes, which are wrapped in paragraph tags. This is accomplished by testing the .nodeType
property of the element. This DOM property holds a numeric code indicating the node's type—text nodes use the code 3
. The contents are again filtered, this time for <br />
elements, and then these elements are removed.