thank_you
thank_you

Reputation: 11107

Targeting elements way up the tree

I'm needing to grab a specific element. I have an event that triggers when I click the a tag. I'm having trouble reaching it since I can only effect the ul that the a tag is inside. The element I want to select has a class of target. The obvious answer is to select target, but there are multiple target classes. My question is how do I target the element I want. Below is the code.

<div id="section">
    <div id="target">
        Here is the div that I want to target. But I can't target it.
    </div>

    <div>
        <ul>
            <li></li>
            <a>Clicking here triggers the event.</a>
            <li></li>
        </ul>
    </div>
</div>

<script>
    $(a).parentsUntil('#section').children(':gt(0)').children(':gt(2)').css('color','red');
</script>

Upvotes: 0

Views: 51

Answers (2)

Ohgodwhy
Ohgodwhy

Reputation: 50798

$('a').parents('#section').find('#target').css('color', 'red');

Upvotes: 1

Sushanth --
Sushanth --

Reputation: 55750

Firstly you need to enclose your code in DOM Ready Handler..

$(function() {
    // Your code Here
});

Secondly your selector is wrong

Supposed to be $('a') instead of $(a)

Try this code

$(this).closest('div').prev('#target').css('color', 'red');

OR

$('a').parents('#section').find('#target').css('color', 'red');

CHECK DEMO

$(function() {
    $('a').on('click', function() {

        $(this).closest('div').prev('#target').css('color', 'red');
    });
});​

Upvotes: 1

Related Questions