Search code examples
jqueryhtmllistthisindicator

How to change a nested image in a div?


I have a list of questions and answers that are being served by a database. (Below in equivalent of how the data will be presented.)

HTML

<div class="question"><img class="allImg" src="faq-right.png"/> this is a question</div>
<div class="answer">and this is an answer</div>


<div class="question"><img class="allImg" src="faq-right.png"/> why is water wet?</div>
<div class="answer">because of bonding molecules</div>


<div class="question"><img class="allImg" src="faq-right.png"/> why is the sky blue?</div>
<div class="answer">the guy with the afro painted it that way</div>


<div class="question"><img class="allImg" src="faq-right.png"/> chickens and roads, who cares? </div>
<div class="answer">only the eggs</div>

JQUERY

<script>
$(document).ready(function(){
    $(".answer").hide();
    $(".question").click(function(){
        $(".answer").slideUp();
        $(".allImg").attr('src','faq-right.png');
        if(!$(this).next().is(":visible"))
        {
            $(this).next().slideDown();
            $(".allImg").attr('src','faq-down.png');
        }
    })
});
</script>

I can get the individual questions to show/hide. And with the current code, the arrow indicating which question is active changes on all questions. I just need it to change on the one that is clicked.

(I attempted using variations of "this" and img attr, but all attempts have failed so far.)

There is some room for code restructure, but at this time, there are no id being generated for each question.

enter image description here


Solution

  • Change your selector to $(this).find(".allImg").attr('src','faq-down.png');

    $(document).ready(function(){
        $(".answer").hide();
        $(".question").click(function(){
            $(".answer").slideUp();
            $(".allImg").attr('src','faq-right.png');
            if(!$(this).next().is(":visible"))
            {
                $(this).next().slideDown();
                $(this).find(".allImg").attr('src','faq-down.png');
            }
        })
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="question"><img class="allImg" src="faq-right.png"/> this is a question</div>
    <div class="answer">and this is an answer</div>
    
    
    <div class="question"><img class="allImg" src="faq-right.png"/> why is water wet?</div>
    <div class="answer">because of bonding molecules</div>
    
    
    <div class="question"><img class="allImg" src="faq-right.png"/> why is the sky blue?</div>
    <div class="answer">the guy with the afro painted it that way</div>
    
    
    <div class="question"><img class="allImg" src="faq-right.png"/> chickens and roads, who cares? </div>
    <div class="answer">only the eggs</div>