0

I am adding a option to a select that is input by a user:

function prependToSelect(userInput){
  $('#x').prepend('<option>' + userInput + '</option>');
}

what is the safest and most simple way to make sure there is nothing dangerous in userInput that can break the javascript or html? It would also be good if the solution/function would be reusable in different scenarios.

user1985273
  • 1,817
  • 15
  • 50
  • 85

2 Answers2

3

My inital answer would be to create a options element and set the innerText instead of innerHTML

but since u use jQuery...

$('#x').prepend($('<option>', {text: userInput}))
Endless
  • 34,080
  • 13
  • 108
  • 131
2

Don't add it as HTML.

document.querySelector("#x")
        .appendChild(document.createElement("option"))
        .textContent = userInput;

This adds it as .textContent so no HTML will be parsed, so no danger.