0

I want to count element dynamically and generate code as per elements are available in HTML

here is code:

$(window).load(function(){                                                

var count= $(".accordion .toggle").length;
var i;

for(i=0; i<=count; i++){
    $(".accordion li a").eq(i).click(function(){
    alert(i+" image");
    $(".accordian-left-image img").attr('src','https://img'+i+'.jpg');
    });
}; });

Code Details: .accordion .toggle is elements and it's generated dynamically, between for loop code its works when I click on the element it will show img src="img1.jpg" the same thing I want that works when 2nd elements are available and img2.jpg is available.

the issue I am facing is if elements are available 6 then code generate 6th for all elements. but I want to be separated for all.

3
  • 1
    Can you please provide your html as well and put it into a working snipped? Commented Nov 6, 2018 at 10:39
  • I don't understand your question, you say that with your code you are getting for 6 elements the image img6.jpg for all of them? Commented Nov 6, 2018 at 10:40
  • You don't need a loop for this. Assuming your HTML is structured well then you can just use DOM traversal. We'd need to see your HTML to give you an example of this, though Commented Nov 6, 2018 at 10:43

1 Answer 1

1

This is because $(".accordian-left-image img").attr('src','https://img'+i+'.jpg'); selects every accordian-left-image class. To fix this, use the .eq() selector:

$(".accordian-left-image img").eq(i).attr('src','https://img'+i+'.jpg');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.