how can i write this code with one function?
function myFunction1() {
document.querySelector("#demo").innerHTML = document.querySelector("#demo1").innerHTML;
}
function myFunction2() {
document.querySelector("#demo").innerHTML = document.querySelector("#demo2").innerHTML;
}
function myFunction3() {
document.querySelector("#demo").innerHTML = document.querySelector("#demo3").innerHTML;
}
function myFunction4() {
document.querySelector("#demo").innerHTML = document.querySelector("#demo4").innerHTML;
}
function myFunction5() {
document.querySelector("#demo").innerHTML = document.querySelector("#demo5").innerHTML;
}
function myFunction6() {
document.querySelector("#demo").innerHTML = document.querySelector("#demo6").innerHTML;
}
4
Answers
Use a parameter on the function: (i’ve named it
n
, but you can name it something else if that sounds better to you)Just pass the element that the function should work with into the function as an argument.
Here’s how you can do it:
Making the target ID a parameter would indeed enhance the flexibility and reusability of the function.
You could try adding the function to the
window
object dynamically.A better way would be to pass the selector:
Alternatively,