Convert Element to Option
Is there a way to convert an Element Object to an HTMLOption object? I have one code that looks like this:
var request = getXMLHttpRequest();
request.onreadystatechange =
function (){
if(request.readyState == 4 && request.status == 200){
开发者_开发知识库 var regions = request.responseXML.firstChild;
document.getElementById('selectedRegiao').appendChild(regions.childNodes[1]);
}
}
request.open("get", "getRegions.php?country=" + country,true);
request.send();
I know that this code does not work and is not specified but I think It is enough to give the idea about what I am trying to accomplish. The element with the id selectedRegiao is a <select>
tag.<br>
regions is XML. It looks like this:
<option name="val1">val1</option>
<option name="val2">val2</option>
I wanted to convert it in a quick and easy way to an Option tag. I know how to do it in the long way but. Is there a direct and quick way to do it?
You should be able to get the option elements from XML using
var optsFromXml = regions.getElementsByTagName('option');
That would give you an options collection to handle in html. Like appending to some <select>
element:
someSelect.appendChild (
new Option( optsFromXml[0].getAttribute('name') )
); //=> appends option with value/text from name attribute
you could do something like this:
var newOpt = new Option(document.getElementById('selectedRegiao').innerHTML, document.getElementById('selectedRegiao').value);
selectObject.options[index] = newOpt;
精彩评论