Brian Coolidge
Brian Coolidge

Reputation: 4649

Multiple element, same class, get value of one element - jquery

I have this multiple elements with the same class.

<div class="test-container">
    <a class="dup-class">
        Get Value
    </a>

    <div class="product-list-col">
        1
    </div>
</div>

<div class="test-container">
    <a class="dup-class">
        Get Value
    </a>

    <div class="product-list-col">
        2
    </div>
</div>

<div class="test-container">
    <a class="dup-class">
        Get Value
    </a>

    <div class="product-list-col">
        3
    </div>
</div>

If I click the the <a> tag on the first div, it should alert the value of .product-list-col value which is 1

if I click the second div of anchor tag, it should alert 2

here's the code for it

$(".dup-class").on('click', function() {
    cont = $(this + " .product-list-col").text();
    alert(cont);
});

Any solution for this stuff?

Here's the jsfiddle of it: http://jsfiddle.net/Vigiliance/PLeDs/3/

Upvotes: 2

Views: 4936

Answers (2)

Ashish Kumar
Ashish Kumar

Reputation: 3039

do this:

$(".dup-class").on('click', function() {
    cont = $(this).next().text(); // this is the line where change done
    alert(cont);
});

http://jsfiddle.net/PLeDs/2/

Upvotes: 1

Anton
Anton

Reputation: 32581

You could use siblings(), the reason why your code doesn't work is because it's selecting all .product-list-col

$(".dup-class").on('click', function () {
    cont = $(this).siblings('.product-list-col').text();
    alert(cont);
});

or use .next()

$(".dup-class").on('click', function () {
    cont = $(this).next('.product-list-col').text();
    alert(cont);
});

Upvotes: 4

Related Questions