Reputation: 117
I want get test
inside this example. Why it doesn't work?
HTML
<div id="partTypes">
<div class="partType">
<div class="details"> <span class="name">test</span>
</div>
<div class="buttons">
<input class="addCart" type="button" value="click me" />
</div>
</div>
</div>
JAVASCRIPT
$(document).ready(function () {
$('input.addCart').live('click', function () {
var $partType = $(this).closest('div.partType');
alert($partType.filter('span.name').text());
});
});
Upvotes: 1
Views: 37667
Reputation: 110
Try this:
$(document).ready(function () {
$('input.addCart').click(function () {
var $partType = $(this).closest('div.partType');
alert($partType.find('span.name').text());
});
});
Upvotes: 2
Reputation: 207861
Change:
alert($partType.filter('span.name').text());
to:
alert($partType.find('span.name').text());
Ideally you also want to stop using .live()
and move to .on()
(since live was deprecated awhile ago and removed in 1.9) so the whole block would be:
$('input.addCart').on('click', function () {
var $partType = $(this).closest('div.partType');
alert($partType.find('span.name').text());
});
Upvotes: 5
Reputation: 388316
.filter()
will apply the filter to the passed set of elements, where as you want to look at the descendent elements for which you need to use find()
$(document).ready(function () {
$('input.addCart').live('click', function () {
var $partType = $(this).closest('div.partType');
alert($partType.find('span.name').text());
});
});
.filter(): Reduce the set of matched elements to those that match the selector or pass the function's test.
.find(): Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
Upvotes: 1