简体   繁体   中英

Getting “InvalidCharacterError: String contains an invalid character” for an option in list box

I have the following line in my jsp file:

var option = document.createElement('<option value="NO">');     

Not sure why this gives me InvalidCharacterError .

Any alternatives?

You can use this code to add to your tag.

var myoption = document.createElement("option");
myoption.setAttribute("value", "carvalue");
var text = document.createTextNode("maruti");
myoption.appendChild(text);
document.getElementById("mySelect").appendChild(myoption);

There was a change in DOM implementation. Before, you could create a new element with the code inside, for instance:

BAD

var anElement = document.createElement("<A HREF=\"http://stackoverflow.com \">StackOverflow</A>")

This implementation now, returns this 'InvalidCharacterError'. What you must do now is to create the element and to populate it using the innerHTML attribute or the different specific attributes for any node.

GOOD

var anElement = document.createElement("a")
anElement.innerHTML = ("<A HREF=\"http://stackoverflow.com \">StackOverflow</A>")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM