I have a button that when clicked calls a function that randomizes a number inside of it. Then I have another button that when it’s clicked it clones the first button.
What I want to do is to turn the cloned button independent from the original (while using the same function), but when it’s clicked, instead of calling the function and randomizing its own number, it randomizes it’s parent’s. How can I make this work? I’m using jQuery.
$(document).ready(function() {
$('body').on('click', '#button1', function() {
document.querySelector('#num1').textContent = Math.floor(Math.random() * 6 + 1);
});
$('#clone1').on('click', function() {
console.log("lolo");
const place = $('#place');
$('#block1').clone().appendTo(place);
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
</head>
<body>
<div class="section1">
<div class="block" id="block1">
<button class="button" id="button1">
<div class="num" id="num1">1</div>
</button>
</div>
<div class="section2">
<button class="clone1" id="clone1">clone1</button>
<div class="place" id="place">
</div>
</div>
</body>
</html>
2
Answers
It was because the button to be edited was being selected by the id:
Instead, have the handler edit the event target:
Don’t use IDs, which are supposed to be unique, use classes.
Then the event handler can use
$(this)
to find the element with the class inside the button.