Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Find Div within Parent

Tags:

jquery

I'm not sure I worded this correctly. But I have an HTML document setup something similar to this.

<div id="intro_page" class="sub_page">

        <div class="sub_header"><img src="assets/img/intro_header.jpg" /></div>

        <div class="video_holder">
            <video class="video_player"></video>
        </div>

        <div class="page_text"><img src="" width="1020" /></div>


</div><!-- /intro_page -->

and

<div id="spark_page" class="sub_page car_page">

            <div class="sub_header"><img src="assets/img/header.jpg" /></div>

            <div class="video_holder">
                <video class="video_player"></video>
            </div>

            <ul class="car_story">
                <li data-text="story1_text"><img src="assets/img/story1_btn2.jpg" /></li>
                <li><img src="assets/img/story2_btn2.jpg" /></li>
                <li><img src="assets/img/story3_btn2.jpg" /></li>
            </ul>


            <div class="page_text"><img src="" width="1020" /></div>

</div><!-- /spark_page -->

I'm trying to target the page_text div if someone clicks on a car_story li. But because there are two divs that have page_text, I don't know how to target the one which is in the same parent div as the car_story ul. Hope this makes sense. Thanks!

I've tried things similar to this, but with no luck.

$(".car_story li").click(function() {

    $(this).parent().find(".page_text img").attr("src","newimage.jpg");

});
like image 814
Jako Avatar asked Nov 13 '12 16:11

Jako


3 Answers

Pass in the closest div.sub_page as the context in the selector, then the element you want to find

$(".car_story li").click(function() {
    var parent = $(this).closest('.sub_page'); // find closest sub_page
    $(".page_text img",parent).attr("src","newimage.jpg"); // find img inside of closest sub_page
});
like image 114
wirey00 Avatar answered Sep 25 '22 00:09

wirey00


$(".car_story li").click(function() {
    $(this).parents("div").find(".page_text > img").attr("src","newimage.jpg");
});
like image 43
Adriano Carneiro Avatar answered Sep 26 '22 00:09

Adriano Carneiro


Try closest()

$(".car_story li").click(function() {

    $(this).closest('.sub_page').find(".page_text img")
                                .attr("src","newimage.jpg");

});
like image 32
Sushanth -- Avatar answered Sep 23 '22 00:09

Sushanth --