I want to create a button in javascript using innerHTML
I try to search online, but all the answers all suggest me to use document.createElement('')
, but this doesn't help me at all.
Here is the code:
var result = document.querySelector('result');
let arr = [1,2,3,4,5,6]
function display(){
//.....
}
for (let i = 0; i <arr.length;i ){
//...... hide some code here
if(i == arr.length - 1){
result.innerHTML = "<button onclick = 'display()'>" "Show more" "</button>"
}
<div id="result"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
This code displays Uncaught SyntaxError: Unexpected end of input
and doesn't work at all.
Could someone explain to me a little bit why using innerHTML
to make a button doesn't work and give me a better solution?
Thanks for any responds.
CodePudding user response:
Just a couple things. You are getting unexpected end of input because you are missing a } at the end.
The second one, in order for the querySelector to work, you need to add a # since you are selecting by id and not by tag.
This example should work.
var result = document.querySelector('#result');
let arr = [1,2,3,4,5,6]
function display(){
//.....
}
for (let i = 0; i <arr.length;i ){
//...... hide some code here
if(i == arr.length - 1){
result.innerHTML = "<button onclick = 'display()'>" "Show more" "</button>"
}}
<div id="result"></div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
InnerHTML reparses and recreates all DOM nodes within the div element, which is inefficient compared to just attaching a new element to the div.
Look at this:
https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement
How you want to use it:
let btn = document.createElement("button");
btn.innerHTML = "Show more";
btn.onclick = display();
document.body.appendChild(btn);
CodePudding user response:
no any big issues in the code; you just ignored to add a } at the end to close the "If statement block". Other mistake is you need to use # in the query selector if you are using it by "ID". Your ID is result, so make it #result
var result = document.querySelector('#result');
let arr = [1,2,3,4,5,6]
function display(){
//.....
}
for (let i = 0; i <arr.length;i ){
//...... hide some code here
if(i == arr.length - 1){
result.innerHTML = "<button onclick = 'display()'>" "Show more" "</button>"
}}
<div id="result"></div>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>