hlapointe
hlapointe

Reputation: 117

get text by class in jquery

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

Answers (3)

Eyal
Eyal

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

j08691
j08691

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());
});

jsFiddle example

Upvotes: 5

Arun P Johny
Arun P Johny

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

Related Questions