Home > Back-end >  what is the right way to write this code?
what is the right way to write this code?

Time:11-01

im pretty sure the tabelist.innerHTML = '<option>invalid value</option>'

isn't the best way to make an element and insert it in another one, but how i am supposed to do this if is not this way?

let submit = document.querySelector('input#submit')
let tabelist = document.querySelector('select#tabe')
submit.addEventListener('click', clicar)
function clicar(){
    let tabenumber = 1
    let number = Number(document.querySelector('input#number').value)
    if(number == ''){
        tabelist.innerHTML = '<option>invalid value</option>'
    }else{
        tabelist.innerHTML = ''
        for(number*tabenumber; tabenumber <=10; tabenumber  ){
            tabelist.innerHTML  = `<option>${number} x ${tabenumber} = ${number*tabenumber} </option>`
        }
    }
}

CodePudding user response:

.innerHTML is valid, but should only be used as a last resort because it has potential side effects of:

  • wiping out event handlers that were set on elements that are now being replaced
  • slowing down the rendering of the page because the HTML parser must parse the new content
  • potentially exposing a security hole by allowing malicious script to execute

Another approach would be to use the Document Object Model to create, configure and inject an element:

const list = document.querySelector("select");

// Create new element
const option = document.createElement("option");

// Configure new element
option.textContent = "Item 1";

// Inject into existing element
list.appendChild(option);
<select>

</select>

  • Related