I want to change the HTML code on the button click. Is there any other way to accomplish this? The issue I have faced is that over time ex1,ex2 codes get bigger and it becomes hard to read due to a text being a string.
<button onclick="test (1)">
click
</button>
<button onclick="test (2)">
click
</button>
<div id="ex1"></div>
const faq = {
ex1: `<button>1</button>`,
ex2: `<button>2</button>`
}
function test (number) {
if (number == 1){
document.getElementById("ex1").innerHTML = (faq.ex1);
}
if (number == 2){
document.getElementById("ex1").innerHTML = (faq.ex2);
}
}
You just needed to remove the space between your function invocation.
Instead of this:
test (1)
do this
test(1)
Also you need to remove the space between your function name and the parenthesis
Instead of this
function test ()
Do this
function test()
Also you need to put your javascript into a script tag and make sure it comes before the html that calls it. See example snippet
<script>
const faq = {
ex1: `<button>1</button>`,
ex2: `<button>2</button>`
}
function test(number) {
if (number == 1){
document.getElementById("ex1").innerHTML = (faq.ex1);
}
if (number == 2){
document.getElementById("ex1").innerHTML = (faq.ex2);
}
}
</script>
<button onclick="test(1)">
click
</button>
<button onclick="test(2)">
click
</button>
<div id="ex1"></div>