2

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/

2 Answers 2

4

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);
});
Sign up to request clarification or add additional context in comments.

2 Comments

I'd say that siblings is a much better option because next would be bound to the current DOM formations...
You can also do this by having jQuery search for the element within the parent(), by proving context to the jQuery search as a second parameter: $('.product-list-col',$(this).parent()).text(); in case the element stops being the sibling. api.jquery.com/jquery/#selector-context
1

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/

3 Comments

This technically works, but is a bad idea as it will break as soon as the DOM structure changes.
This solution was for a specific kind of problem. If you are sure that next element will be this only, you do this, otherwise we have options like siblings('.someclass')
I was just pointing out that it would be bad practice to rely on DOM structure being fixed and never changing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.