سؤال

I'm tinkering a bit with jquery to show a hidden div when a link is clicked. This should be fairly simple, but there's a flaw to it in this case. I have the following markup:

<div class="first-row">
        <div class="week">
            <p>Uge 2</p>
            <p>(08-01-11)</p>
        </div>
        <div class="destination">
            <p><a href="#">Les Menuires</a></p>
            <p>(Frankrig)</p>
        </div>
        <div class="days">4</div>
        <div class="transport">Bil</div>
        <div class="lift-card">3 dage</div>
        <div class="accommodation">
            <p><a class="show-info" href="#">Hotel Christelles (halvpension)</a></p>
            <p>4-pers. værelse m. bad/toilet</p>
        </div>
        <div class="order">
            <p><a href="#">2149,-</a></p>
            <p class="old-price">2249,-</p>
        </div>
        <div class="hotel-info">
         <!-- The div I want to display on click -->
        </div>
    </div>

When I click the "show-info" link I want the "hotel-info" div to display. My backend devs don't want me to use ids (don't ask me why..) and the above markup is used over and over again to display data. Therefore I need to be able to access the "hotel-info" div in the "first-row" div where the link is clicked.

I've tried to do something like:

$(document).ready(function() {
    $('.show-info').click(function() {
        var parentElement = $(this).parent().parent();
        var lastElementOfParent = parentElement.find(".show-hotel");
        lastElementOfParent.show();
    });
});

But without a result :-/ Is this possible at all?

Any help is greatly appreciated!

Thanks a lot in advance!

هل كانت مفيدة؟

المحلول

Try this:

$('.show-info').click(function() {
    $(this).closest('.accommodation').siblings('.hotel-info').show();
});

Even better imo, as it would be independent from where the link is in a row, if every "row div" has the same class (I assume only the first one has class first-row), you can do:

$(this).closest('.row-class').find('.hotel-info').show();

Reference: .closest, .siblings


Explanation why your code does not work:

$(this).parent().parent();

gives you the div with class .accommodation and this one has no descendant with class .hotel-info.

It is not a good idea to use this kind of traversal for more than one level anyway. If the structure is changed a bit, your code will break. Always try to use methods that won't break on structure changes.

نصائح أخرى

You're right in not using an ID element to find the DIV you want :)

Use closest and nextAll

Live demo here : http://jsfiddle.net/jomanlk/xTWzn/

$('.show-info').click(function(){
    $(this).closest('.accommodation').nextAll('.hotel-info').toggle();
});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top