Reputation: 21
So, basically, what I need to do is to get every image from the page that I'm currently on (in this case I've got 2) and I need to insert a button to it. The approach that I'm trying is targeting all the images, and placing a button in their parent div. I've attempted to achieve this with the following code:
<!DOCTYPE html>
<html>
<head>
<style>
.container {
position: relative;
width: 100%;
max-width: 400px;
}
.container img {
width: 100%;
height: auto;
}
.container .btn {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
background-color: #555;
color: white;
font-size: 16px;
padding: 12px 24px;
border: none;
cursor: pointer;
border-radius: 5px;
text-align: center;
}
.container .btn:hover {
background-color: black;
}
</style>
</head>
<body>
<div class="container">
<img src="123.png">
</div>
<div class="container">
<img src="223.png">
</div>
<script type="text/javascript">
var imgscount = document.querySelectorAll("img")
var imgs_array = [...imgscount];
for(var i = 0; i< document.images.length; i++)
{
var imgs = document.querySelector("img");
for (var j = 0; j < imgs_array.length-1; j++)
{
imgs.parentElement.innerHTML = imgs.parentElement.innerHTML +'<button class="btn">Button</button>';
};
};
</script>
</body>
</html>
Although, imgs.parentElement.innerHTML = imgs.parentElement.innerHTML +'<button class="btn">Button</button>';
creates two buttons in the same <div>
, instead of 1 button per each <div>
.
This image should explain better what I'm trying to achieve here.
Upvotes: 0
Views: 122
Reputation: 3090
One simple loop would do the trick, also I manually draw the circle to replace the images
var images = document.querySelectorAll("img");
for ( var i = 0; i < images.length; i++ ) {
images[i].parentElement.innerHTML += '<button class="btn">Button</button>';
}
.container {
position: relative;
/*
width: 100%;
max-width: 400px;
*/
width: 200px;
height: 200px;
border-radius: 50%;
border-width: 3px;
border-color: black;
border-style: solid;
}
.container img {
width: 100%;
height: auto;
}
.container .btn {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
background-color: #555;
color: white;
font-size: 16px;
padding: 12px 24px;
border: none;
cursor: pointer;
border-radius: 5px;
text-align: center;
}
.container .btn:hover {
background-color: black;
}
<div class="container">
<img src="123.png">
</div>
<div class="container">
<img src="223.png">
</div>
Upvotes: 0
Reputation: 1239
just remove this for loop
for (var j = 0; j < imgs_array.length-1; j++)
Upvotes: 1