I want to change the src attribute, for each <li> <img>
. When i click a button, i want for each img src attribute to be changed with the one in the code.
My code does work, but only for the first element. Can you give me an idea please? Thank you.
$("p").click(function() {
var menu = $("img");
for (var i = 0; menu[i]; i++) {
const menuElement = menu[i];
if ($(menuElement).attr("src") != "dsdassdada.jpg") {
$(menuElement).attr("src", "image1.jpg");
break;
}
}
});
img {
width: 50px;
}
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<p>sdadsa</p>
<ul>
<li>
<img src="https://www.publicdomainpictures.net/pictures/130000/nahled/red-box-background.jpg" />
</li>
<li>
<img src="https://www.publicdomainpictures.net/pictures/130000/nahled/red-box-background.jpg" />
</li>
<li>
<img src="https://www.publicdomainpictures.net/pictures/130000/nahled/red-box-background.jpg" />
</li>
<li>
<img src="https://www.publicdomainpictures.net/pictures/130000/nahled/red-box-background.jpg" />
</li>
</ul>
It's actually much easier just to iterate directly from the $('img')
selector, using $(this)
in each iteration to refer to the image
Here, we go through the images one by one and if the source isn't "image1.jpg" or "dsdassdada.jpg", then we change it, and set a variable so our loop stops looking.
Rather than doing a if(src=='this' || src=='that')
I opted for a shorthand if (array_of_imgs.includes(this_src))
let newsrc = "image1.jpg";
$("p").click(function() {
let found = false
$("img").each(function() {
if (found) return;
if (![newsrc, "dsdassdada.jpg"].includes($(this).attr("src"))) {
$(this).attr("src", newsrc);
found = true
}
})
});
img {
width: 50px;
}
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<p>sdadsa</p>
<ul>
<li>
<img src="https://www.publicdomainpictures.net/pictures/130000/nahled/red-box-background.jpg" />
</li>
<li>
<img src="https://www.publicdomainpictures.net/pictures/130000/nahled/red-box-background.jpg" />
</li>
<li>
<img src="https://www.publicdomainpictures.net/pictures/130000/nahled/red-box-background.jpg" />
</li>
<li>
<img src="https://www.publicdomainpictures.net/pictures/130000/nahled/red-box-background.jpg" />
</li>
</ul>