style.display='none' doesn't work on o

2019-01-01 13:31发布

ok, heres some sample code that demonstrates the problem. if i click the button in firefox, the first option disappears. if i click the button in chrome, nothing happens, or rather if i inspect the first option, it does have the attribute "style='display:none'" but the option itself on the html page is not hidden.

<form>
<select>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<input type="button" onclick="document.getElementsByTagName('option')[0].style.display='none'" value="hide option 1">
</form>

why doesn't this work in chrome?

8条回答
流年柔荑漫光年
2楼-- · 2019-01-01 14:16
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
removeIt = function()
{
    var theSelect = document.getElementById("theSelect");
    var theOption = document.getElementById("theOption");
    theSelect.removeChild(theOption);
};
</script>
</head>
<body>
<select id="theSelect">
<option>1</option>
<option id="theOption">2</option>
<option>3</option>
</select>
<input type="button" onclick="removeIt()" value="remove it!"/>
</body>
</html>

I quickly got it working by simply removing it from its parentNode... obviously this is going to be a hack.
I'll try to find a better solution for you =)

By the way, welcome to Stack Overflow

查看更多
爱死公子算了
3楼-- · 2019-01-01 14:25

The question is rather why that works in any browser at all?

The options are not used as elements in the page, they contain the information to show in the select element. Some browsers let you apply some styles to the options, but generally you can't really expect cross browser support for any styles at all.

If you want to keep an option from being displayed, you just have to remove it from the select.

查看更多
登录 后发表回答