Reputation: 503
I am trying to create two child divs either of which when clicked will give a "highlight" class to the "toggler" class child div ONLY. I am creating a "toggler" selector variable which hold the "toggler" class. However, given the following code, both children divs are given the "highlight" class as opposed to just the "toggler" class which the selector variable is set up to hold.
HTML:
<div class="parent_div">
<div class="first_child">
First Child Text
</div>
<div class="toggler">
Toggler
</div>
</div>
CSS:
.parent_div > div {
display: inline-block;
float: left;
clear: both;
}
.parent_div > div:hover {
cursor: pointer;
}
.highlight {
background-color: yellow;
}
jQuery:
$(document).ready(function() {
var toggler = $('.toggler');
var eitherChild = $('.first_child, .toggler');
eitherChild.click(function() {
var thisParent = $(this).parent();
thisParent.children(toggler).toggleClass('highlight');
});
});
A fiddle to show the results: http://jsfiddle.net/bronzegate/5yTBP/
Changing the jQuery to the following yields the desired results:
$(document).ready(function() {
var eitherChild = $('.first_child, .toggler');
eitherChild.click(function() {
var thisParent = $(this).parent();
thisParent.children('.toggler').toggleClass('highlight');
});
});
A fiddle to show the results: http://jsfiddle.net/bronzegate/ZS8P5/
Why does the Children method in the former case select both of the children and not exclusively the children that are defined in the "toggler" selector variable?
Upvotes: 2
Views: 76
Reputation: 4652
The children() function accepts a selector:
http://api.jquery.com/children/
.children( [selector ] )
Returns: jQuery
Description: Get the children of each element in the set of matched elements, optionally filtered by a selector.
selector: A string containing a selector expression to match elements against.
In the first case (the wrong one), you're passing an object, which fails:
var toggler = $('.toggler');
In the second case, you're passing just the selector ('.toggler'), which is why it works as expected.
Upvotes: 1
Reputation: 44740
Because .children()
only accept selector
and not a jquery object
Upvotes: 0
Reputation: 196002
Because the .children()
method only accepts a string selector for filtering.. not an element.
Quote
.children( [selector ] )
selector
Type: Selector
A string containing a selector expression to match elements against.
What you try to achieve could be done with .filter()
(which does accept an element or jQuery object as a parameter) but still it makes no sense in this case..
thisParent.children().filter(toggler).toggleClass('highlight');
Upvotes: 0