JQuery Find Div Inside Parent

I’m not sure that it was formulated correctly. But I have an HTML document that installs 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 am trying to target the page_text div if someone clicks on car_story li . But since there are two page_text that have page_text , I don’t know how to target one that is in the same parent div as car_story ul . Hope this makes sense. Thanks!

I tried similar things but no luck.

 $(".car_story li").click(function() { $(this).parent().find(".page_text img").attr("src","newimage.jpg"); }); 
+4
source share
4 answers

Go to the nearest 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 }); 
+10
source
 $(".car_story li").click(function() { $(this).parents("div").find(".page_text > img").attr("src","newimage.jpg"); }); 
+2
source

Try closest()

 $(".car_story li").click(function() { $(this).closest('.sub_page').find(".page_text img") .attr("src","newimage.jpg"); }); 
0
source

This has the same result, but I think it’s more clear what result you will get in all cases (for example, if you had a different page, possibly related to the fact that I also had an identity with the car_story class, then this The click event will still fire only for spark_page.):

 $(".car_story li").click(function() { $('div#spark_page').find(".page_text img").attr("src","newimage.jpg"); }); 

Of course, if you were in ajax in more html with li car_story s and wanted to change the source of all .page_text img, then I think you could do

 $(".car_story li").click(function() { $(".page_text img").attr("src","newimage.jpg"); }); 
0
source

Source: https://habr.com/ru/post/1445806/


All Articles